Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.append() behaves differently for Python dictionaries initialized from two different methods

ky     =  ['a','b','c']

val    = 15

dict_1 = dict.fromkeys(ky,[])

dict_1['a'].append(val)

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

dict_2['a'].append(val)

print(dict_1)

print(dict_2)

>Solution :

Please correct me if I’m wrong, but given your post, I’m presuming your question is why dict_1 has the same value (15) for all its keys a, b, and c as the end result, right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If so, I agree that this is unintuitive behavior at a first glance, but what is happening is that by passing [] (an empty list) as the second optional argument for the fromkeys method, you’re populating dict_1 dictionary with references to the same single empty list, hence, when you append val to the key a, all other keys are updated with the same value as well (you passed the empty list as reference. see difference between passing by reference vs passing by value ).

As you noticed yourself, there are other ways to initialize a dictionary of empty lists in Python (as you did "manually" with dict_2).

In case you’re interested in another "less manual" way to initialize a dictionary of empty lists in Python, you could use a list comprehension to do so, as in the following example:

dict_3 = {k : [] for k in ky}

That would initialize dict_3 with empty lists (passed by value), thus, keys b and c would be unaffected when you append val to the key a.

I hope that helps to clarify your example. Kind regards.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading