迭代字典并在数组中存储值

时间:2016-03-03 23:47:54

标签: python arrays dictionary

我有一个字典[{'abc':10,'efg':20,'def':30},{'abc':40,'xya':20,'def':50}]的列表,我想创建一个数组abc[]并在该数组中存储相应的值。所以输出应该看起来像

abc[10,40]
def[30,50]
efg[20]

依此类推,使用python。

1 个答案:

答案 0 :(得分:0)

任何确切的解决方案都可能涉及exec()或更奇怪的东西,大多数Python程序员可能会鼓励你将词典列表更改为列表字典:

from collections import defaultdict

list_of_dictionaries = [
    {'abc':10,'efg':20,'def':30},
    {'abc':40,'xya':20,'def':50},
]

dictionary_of_lists = defaultdict(list)

# there's probably some clever one liner to do this but let's keep
# it simple and clear what's going when we make the transfer:

for dictionary in list_of_dictionaries:
    for key, value in dictionary.items():
        dictionary_of_lists[key].append(value)

# We've achieved the goal, now just dump dictionary_of_lists to prove it:

for key, value in dictionary_of_lists.items():
    print(key, value)

哪个输出:

xya [20]
def [30, 50]
abc [10, 40]
efg [20]

不完全是你所要求的,但在大多数情况下,应该是你需要的。