1

I am trying to initialize a Python dictionary of 12 keys, all set to empty lists to later populate with different values. Here is a simplified example of the issue

The naive solution returns the desired results but it's unpleasant to see a large body of code:

output = {
    'a': [],
    'b': [],
    'c': []
}

output['a'].append(1)
output['b'].append(2)
output['c'].append(3)

print(output)

{'a': [1], 'b': [2], 'c': [3]}

However, when I attempt to create the dictionary via dict.fromkeys():

output = dict.fromkeys(('a', 'b', 'c'), [])

output['a'].append(1)
output['b'].append(2)
output['c'].append(3)

print(output)

{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

Prior to appending, both methods return the same results - a dictionary of empty lists so I'm confused why the appending behavior is different. Please let me know if more information is needed

martineau
  • 119,623
  • 25
  • 170
  • 301
Benjamin Luo
  • 131
  • 8
  • 1
    it's the same list in each key –  Jan 24 '22 at 20:44
  • 1
    This is a case where you need `output = {x:[] for x in ('a', 'b', 'c')}` – Chris_Rands Jan 24 '22 at 20:47
  • 2
    The documentation for [`dict.fromkeys()`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys) says: "All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead." – shriakhilc Jan 24 '22 at 20:47

1 Answers1

3

All your dictionary entries will reference the same list instance. So there is actually only one list.

In order to get distinct lists, you cannot use the fomkeys() method but a dictionary comprehension would work (because every iteration will create a distinct instance of the list):

output = {k:[] for k in ('a','b','c')}
Alain T.
  • 40,517
  • 4
  • 31
  • 51