【发布时间】:2022-01-12 19:59:44
【问题描述】:
在这篇文章的指导下,我创建了 4 套不同的词典:Python variables as keys to dict。我现在想将所有这些字典合并到 1 个列表中。我尝试了以下方法:
classes = ['apple', 'orange', 'pear', 'mango']
class_dict = {}
store = []
for fruit in classes:
if fruit == "orange":
o = 2
q = 1
else:
o = 0
q = 0
for j in ('fruit', 'o', 'q'):
class_dict[j] = locals()[j]
print (class_dict)
store.append(class_dict)
print ("store: ", store)
输出如下图所示。如您所见,store 仅包含每次附加到它的同一字典的列表。我不确定我哪里出错了,我们将不胜感激!
{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}
store: [{'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]
【问题讨论】:
-
我无法理解您试图实现的目标。请为
print(store)添加所需的输出 -
已经添加了。请参阅我的问题的底部。
-
@peru_45 在我点击“发布您的答案”之前大约三秒钟,您删除了您的另一个问题。这是我写的:pastebin.com/ArJxA2X1
-
@Stef 谢谢你的回答;它帮助了我。如果您想在此处发布我的问题,我将取消删除它。
标签: python list dictionary local