将列表中的字典项添加到字典中

时间:2018-05-24 15:08:56

标签: python list dictionary

大家好,我对这个简单的问题很遗憾。我有一个字典和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'}}]

这可能是其他一些问题的重复,但我无法找到它

2 个答案:

答案 0 :(得分:2)

这是因为您不断将相同的 aux_dict添加到res

您可能要做的是制作dictionary副本;只需将其分配给aux_dict 制作副本。

这就是你制作(浅)副本的方法:

aux_dict = dictionary.copy()

在您的情况下,这就足够了。

答案 1 :(得分:1)

您可以使用list comprehensiondict 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)
相关问题