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

Time:12-29

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)

CodePudding user response:

they are all using the same ref when you use dict.fromkeys() A change to one is a change to all since they are the same object

You could use a dict comprehension instead of append:

keys = ['a','b','c']
value = [0, 0]
{key: list(value) for key in keys}
{'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}

CodePudding user response:

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?

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.

CodePudding user response:

With dict_1 = dict.fromkeys(ky,[]), all keys are mapped to the same (empty) array.

So whenever you change the contents of that array, each one of these keys will (still) point to the same array containing these new contents.

CodePudding user response:

dict_1 = dict.fromkeys(ky,[]) creates a single list and then calls fromkeys. That one list is used for the value paired with each key. One list referenced through all of the keys.

If you want unique lists, use a dictionary comprehension

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

Here, k:[] is evaluated for each key and a new list is created for each value.

  • Related