【问题标题】:Iterate a dictionary and store value in array迭代字典并将值存储在数组中
【发布时间】:2026-02-03 17:55:02
【问题描述】:

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

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

等等,使用python。

【问题讨论】:

  • 因此您希望结果数组的名称成为 dict 键。对吗?
  • 到目前为止您尝试了哪些方法,在尝试实施解决方案时遇到了什么问题?
  • 欢迎来到 *。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。 * 不是编码或教程服务。

标签: python arrays dictionary


【解决方案1】:

任何确切的解决方案都可能涉及 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]

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

【讨论】: