Merging list of dicts in python

自古美人都是妖i 提交于 2020-07-31 05:38:22

问题


I have the dict in python in the following format:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]

I want output something like this:

dict2 = {'a':20, 'b':10, 'c':15 }

How to do it ?


回答1:


I think you can do it with for loop efficiently. Check this:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2 = dict()
for a in range(len(dict1)):
    dict2[dict1[a].get('Name')] = dict1[a].get('value')
print(dict2)

Output:

{'a': 20, 'b': 10, 'c': 15}

This is the easy way:

dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2={dc['Name']:dc['value'] for dc in dict1}


来源:https://stackoverflow.com/questions/62022524/merging-list-of-dicts-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!