大家好,我对这个简单的问题很遗憾。我有一个字典和python中的字典列表,我想循环遍历列表,将每个字典添加到第一个字典,但不知何故,它只是添加最后一个字典与我想出的解决方案。我正在使用Python 3.6.5
这是我尝试过的:
res = []
dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
{"surname": "Doe", "email": "jd@example.com"},
{"surname": "Morrison", "email": "jm@example.com"},
{"surname": "Targetson", "email": "jt@example.com"}
]
for info in dictionary_2:
aux_dict = dictionary
aux_dict["extra"] = info
res.append(aux_dict)
print(res)
期望是:
[{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Doe', 'email': 'jd@example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Morrison', 'email': 'jm@example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}]
这就是我得到
[{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt@example.com'}}]
这可能是其他一些问题的重复,但我无法找到它
答案 0 :(得分:2)
这是因为您不断将相同的 aux_dict
添加到res
。
您可能要做的是制作dictionary
的副本;只需将其分配给aux_dict
不制作副本。
这就是你制作(浅)副本的方法:
aux_dict = dictionary.copy()
在您的情况下,这就足够了。
答案 1 :(得分:1)
您可以使用list comprehension和dict constructor:
在一行中实现此目的dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
{"surname": "Doe", "email": "jd@example.com"},
{"surname": "Morrison", "email": "jm@example.com"},
{"surname": "Targetson", "email": "jt@example.com"}
]
# ...
res = [dict(dictionary, extra=item) for item in dictionary_2]
# ...
print(res)