Merging list of dicts in python

前端 未结 1 1487
旧巷少年郎
旧巷少年郎 2021-01-28 21:18

I have the dict in python in the following format:

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


        
相关标签:
1条回答
  • 2021-01-28 21:56

    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}
    
    0 讨论(0)
提交回复
热议问题