1

I have a dict that holds string keys and list values, initialized like this:

names = ['first name', 'second name', 'last name']
my_dict = dict.fromkeys(names, [])

What I need now is to append a list to a specific key, which I am trying to do like so:

for result in results:
    my_dict[names[0]].append(result.mean())

As this code is inside another loop, I need to loop through the index in name inside my_dict keys and append to each a different list, which should result in something like this:

>>>my_dict
Output: 
{'first name': [1,
  34,
  52,
  2,
  54,
  3],
 'second name': [4,
  22,
  11,
  3,
  -9,
  1],
...]}

But the problem is even though I specify only one key, I get the same values in every key of this dict, like so:

>>>my_dict
Output: 
{'first name': [1,
  34,
  52,
  2,
  54,
  3],
 'second name': [1,
  34,
  52,
  2,
  54,
  3],
...]}

What am I missing?

RafaJM
  • 481
  • 6
  • 17
  • 2
    Does this answer your question? [How do I initialize a dictionary of empty lists in Python?](https://stackoverflow.com/questions/11509721/how-do-i-initialize-a-dictionary-of-empty-lists-in-python) – Kent Shikama Dec 16 '19 at 19:22
  • 2
    When you use `dict.fromkeys(keys, some_object)` then all the keys are referring to the same object. Don't do that – juanpa.arrivillaga Dec 16 '19 at 19:23
  • This appears to be the exact same problem I have, and it answers my question perfectly. Thanks a million – RafaJM Dec 16 '19 at 19:24

0 Answers0