简体   繁体   中英

creating a dictionary from a nested list containing dictionary in python

[{'duration': 634, 'risetime': 1586496046}, 
 {'duration': 473, 'risetime': 1586501927}, 
 {'duration': 608, 'risetime': 1586537843}, 
 {'duration': 536, 'risetime': 1586543678}, 
 {'duration': 577, 'risetime': 1586579648}]

I want to create one dictionary from this list of dictionaries in python ie {'duration': [634, 473, 608, 536, 577],'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]}

a=[{'duration': 634, 'risetime': 1586496046}, 
  {'duration': 473, 'risetime': 1586501927}, 
  {'duration': 608, 'risetime': 1586537843}, 
  {'duration': 536, 'risetime': 1586543678}, 
  {'duration': 577, 'risetime': 1586579648}]

#Initializing an empty dict
b = {'duration':[],'risetime':[]}
#looping through all values of list 'a' & appending values to respective keys in 'b'
for x in a:
    b['duration'].append(x['duration'])
    b['risetime'].append(x['risetime'])

If you are looking for such an output: {'duration': [634, 473, 608, 536, 577], 'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]}

This is a good usecase for collections.defaultdict :

from collections import defaultdict

lst = [
    {'duration': 634, 'risetime': 1586496046}, 
    {'duration': 473, 'risetime': 1586501927}, 
    {'duration': 608, 'risetime': 1586537843}, 
    {'duration': 536, 'risetime': 1586543678}, 
    {'duration': 577, 'risetime': 1586579648}
]

d = defaultdict(list)
for x in lst:
    for k, v in x.items():
        d[k].append(v)

print(d)

Output:

defaultdict(<class 'list'>, {'duration': [634, 473, 608, 536, 577], 'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]})

Try this one:

myList = [{'duration': 634, 'risetime': 1586496046},
 {'duration': 473, 'risetime': 1586501927},
 {'duration': 608, 'risetime': 1586537843},
 {'duration': 536, 'risetime': 1586543678},
 {'duration': 577, 'risetime': 1586579648}]

myDic = {'duration': [], 'risetime':[]}
for x in myList:
    for y in x:
        myDic[y].append(x[y])

print(myDic)

output

{'duration': [634, 473, 608, 536, 577], 'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM