【发布时间】:2021-08-03 02:45:27
【问题描述】:
我有一个循环:
all_rec = {}
for i in range(0, 2):
rec = buildings[best_buildings[i]]['recommendations']
第一次迭代后'rec'的值:
rec = {'a': {'b': 2, 'c': 1}, 'd': {'e': 5}}
第二次迭代后'rec'的值:
rec = {'d': {'e': 4}}
“推荐”的数据类型是字典。如何将此循环产生的所有“rec”字典添加到一个字典“all_rec”中?
我希望“all_rec”看起来像这样:
all_rec = {'a': {'b': 2, 'c': 1}, 'd': {'e': 5}, 'd': {'e': 4}}
在新字典中同时保留 'd': {'e': 5} 和 'd': {'e': 4}。如何在 Python 2.7 中做到这一点?
【问题讨论】:
-
你不能。 Python 中的字典必须有唯一的键。
-
将值改为
list。追加到该列表而不是覆盖。 -
collections.defaultdict 是解决方案,但我需要你的数据来编写代码!
标签: python python-2.7 dictionary