0

Hi I was wondering when creating a nested dictionary use the fromkeys method to created a nested dict does not work.

x=[1,2,3,4,5]
y=[7,8,9,10,11]
zx=dict.fromkeys(x,dict.fromkeys(y,0))

It creates a nested dict but when you try to update it

zx[1][8]+=1

It updates all values for all outerkeys that have the key 8.

I was wondering why this happened when using this function to make a nested dict

user6656104
  • 51
  • 1
  • 10

1 Answers1

1

That's because you associated all keys of the outer dictionary with the same inner dictionary. You first constructed a dictionary with dict.fromkeys(y,0), and then you associate that dictionary with all the keys with: dict.fromkeys(x,...).

A way to construct the dictionary you want is for instance dictionary comprehension:

zx = {k: dict.fromkeys(y,0) for k in x}

Although this looks quite the same it is not: here, we will for every k in x evaluate dict.fromkeys(y,0) again. As a result, the constructed dictionaries will all he equivalent, but not the same object.

Now we obtain the expected:

>>> x=[1,2,3,4,5]
>>> y=[7,8,9,10,11]
>>> zx = {k: dict.fromkeys(y,0) for k in x}
>>> zx
{1: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 2: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 3: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 4: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 5: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}}
>>> zx[1][8]+=1
>>> zx
{1: {8: 1, 9: 0, 10: 0, 11: 0, 7: 0}, 2: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 3: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 4: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}, 5: {8: 0, 9: 0, 10: 0, 11: 0, 7: 0}}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Wouldn't you get unhashable type list? So would I have to make the list tuples? – user6656104 Aug 08 '17 at 17:50
  • @user6656104: but the keys are not lists, the keys are *elements* of the list. Given these elements are hashable (like ints, strings, etc.) then there is no problem. – Willem Van Onsem Aug 08 '17 at 17:51