我试图在列表中匹配来自不同字典的键值,并将它们作为单独的列表。下面是示例格式
originallist=[
{"A":"Autonomous","C":"Combined","D":"Done"},
{"B":"Bars","A":"Aircraft"},
{"C":"Calculative"}
]
#Note: The dictionaries present in the original list may vary in number
#I was trying to acheive the below format
A=["Autonomous","Aircraft"]
B=["Bars"]
C=["Calculative","Combined"]
D=["Done"]
提前感谢您的帮助
最好的选择是使用defaultdict
。
from collections import defaultdict
out = defaultdict(list)
#data is the list in question
for rec in data:
for key,value in rec.items():
out[key].append(value)
defaultdict在键不存在的情况下返回默认值。dict.items
是返回键值对和迭代器的方法。
你可以用pandas来做得更快,但是除非你有一个庞大的数据集,否则这将是过度杀伤。