1

Hi guys I'm pretty lost with this simple problem. I have a dictionary and a list of dictionaries in python and I want to loop over the list to add each dictionary to the first dictionary but somehow it just adds the last dictionary with the solution I came up with. I'm using Python 3.6.5

This is what I've tried:

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)

What I expect is:

[{'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'}}]

And this is what I get

[{'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'}}]

This is probably a duplicate of some other question but I can't manage to find it

Alberto
  • 1,348
  • 2
  • 14
  • 28

2 Answers2

2

This is because you keep adding the same aux_dict to res.

What you probably want to do is make a copy of dictionary; just assigning it to aux_dict does not make a copy.

This is how you make a (shallow) copy:

aux_dict = dictionary.copy()

That would be sufficient in your case.

Kal
  • 1,707
  • 15
  • 29
1

You can achieve this in one line using list comprehension and 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)
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154