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

2024-06-10 05:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我对这个简单的问题很迷茫。我在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'}}]

这可能是其他问题的重复,但我找不到


Tags: namecomiddictionary字典exampleemailres
2条回答

这是因为您不断地将相同的aux_dict添加到res。你知道吗

您可能想做的是复制dictionary副本;仅将其分配给aux_dict并不复制。你知道吗

以下是制作(浅)副本的方法:

aux_dict = dictionary.copy()

对你来说就足够了。你知道吗

您可以使用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)

相关问题 更多 >