0

Can anybody make sense of this:

Method 1

In[25]: dico = {'A': [], 'B': []}
In[26]: dico['A'].append(1)
In[27]: print(dico)
{'B': [], 'A': [1]}

Method 2

In[28]: letters = ['A', 'B']
In[29]: dico = dict.fromkeys(letters, [])
In[30]: print(dico)
{'B': [], 'A': []}
In[31]: dico['A'].append(1)
In[32]: print(dico)
{'B': [1], 'A': [1]}

I cannot figure out why in the 2nd case the value is appended in each key.... this is a serious bug or I am seriously tired.....

martineau
  • 119,623
  • 25
  • 170
  • 301
Baka
  • 73
  • 6

1 Answers1

0

You can do this nicely with a dictionary comprehension:

dico = {k: [] for k in letters}
mgilson
  • 300,191
  • 65
  • 633
  • 696