【问题标题】:Convert python list to dictionary using same default key使用相同的默认键将 python 列表转换为字典
【发布时间】:2022-06-17 20:51:18
【问题描述】:

我有一个如下所示的列表: list = ['a', 'b', 'c']

我想遍历该列表以获取如下字典: dict = {'jobs': [{'id':'a'}], [{'id':'b'}], [{'id':'c'}]}

我尝试循环遍历列表的元素,例如:

dict = {'jobs':[{}]}
for key in range(len(list)):
    dict['jobs'][key]['uid'] = list[key]

print(dict)```

But I get an out of range error.

Any suggestions, please?

Thanks,
Enrico

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    你可以使用:

    list = ['a', 'b', 'c']
    {'jobs' : [{'id' : x} for x in list]}
    
    # {'jobs': [{'id': 'a'}, {'id': 'b'}, {'id': 'c'}]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2015-07-17
      相关资源
      最近更新 更多