0

I am facing a really simple and strange problem with Python.

I have a dict with several keys, that contain empty lists. I want to append/extend the content of lists of specific keys. The code I therefore think of looks like this

d = dict.fromkeys(['A','B','C'],[])
d['A'].append('Hello')

However, the result is not what I expect. The value of each key is a list containing one element: 'Hello'

>>> d
{'A': ['Hello'], 'C': ['Hello'], 'B': ['Hello']}

If I try what follows, it results in the same thing

d.get('A').append('Bye')

What operations I have to do obtain this?

>>> d
{'A': ['Hello'], 'C': [], 'B': []}

Can someone explains what goes wrong with my syntax?

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49

2 Answers2

5

Your syntax is fine, but you're using the same list over and over again. Since lists are mutable, when you append, you're adding 'Hello' to the same list, which happens to be referenced in three places. What you probably want to do instead is create the dict a little more manually:

d = {k:[] for k in ['A', 'B', 'C']}

(The above is Python 2.7 or later. For older Python you can use: dict((k,[]) for k in ['A', 'B', 'C']))

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • I feel [this small tutorial](http://henry.precheur.org/python/copy_list) helped me understand this python concept the best, since it's slightly different and counter intuitive coming for C/++ – Tejas Pendse Mar 10 '14 at 18:00
4

You're creating a dictionary with all its values refer to the same instance [] as @Aशwini चhaudhary mentioned. You may want to use defaultdict:

In [150]: from collections import defaultdict

In [151]: d = defaultdict(list)

In [152]: d['A'].append('Hello')

In [153]: d
Out[153]: defaultdict(<type 'list'>, {'A': ['Hello']})

In [154]: print d['B']
[]
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108