[{'duration': 634, 'risetime': 1586496046},
{'duration': 473, 'risetime': 1586501927},
{'duration': 608, 'risetime': 1586537843},
{'duration': 536, 'risetime': 1586543678},
{'duration': 577, 'risetime': 1586579648}]
我想用python这个字典列表创建一个字典,即{'duration':[634,473,608,536,577],'risetime':[1586496046,1586501927,1586537843,1586543678,1586579648]
答案 0 :(得分:0)
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'])
如果您正在寻找这样的输出:{'duration':[634,473,608,536,577], 'risetime':[1586496046、1586501927、1586537843、1586543678、1586579648]}
答案 1 :(得分:0)
这是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)
输出:
defaultdict(<class 'list'>, {'duration': [634, 473, 608, 536, 577], 'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]})
答案 2 :(得分:0)
尝试这个:
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)
输出
{'duration': [634, 473, 608, 536, 577], 'risetime': [1586496046, 1586501927, 1586537843, 1586543678, 1586579648]}