Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Appending list elements to dictionary in Python

I have a weird problem when trying to append a list of elements to a dictionary. I am not sure what I am doing wrong. Any help is very much appreciated.

here is what I have:

keys = ['a', 'b', 'c']
d = dict.fromkeys(keys, [])
d['a'].append(10)
d['a'].append(11)
d['b'].append(30)
print(d)

the output I am getting is:

{'a': [10, 11, 30], 'b': [10, 11, 30], 'c': [10, 11, 30]}

I would expect:

{'a': [10, 11], 'b': [30], 'c': None}

Thank you

like image 361
RXP Avatar asked Dec 07 '25 14:12

RXP


1 Answers

You are providing an empty list, and fromkeys() uses this particular object for all the keys, so that their corresponding values refer to the same object. When you do d['a'].append(10), it appends 10 to this single object, which all the dict items share, thus resulting in what you are getting now.

Python document mentions this exact situation:

fromkeys() is a class method that returns a new dictionary. value defaults to None. 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.

— https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

Following the suggetion in the python doc, you can do d = {k: [] for k in keys} instead.

like image 63
j1-lee Avatar answered Dec 10 '25 05:12

j1-lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!