0

In Python 3, if I create a dict from dict.fromkeys then it displays a different behavior than just assigning a dict to a variable. I could see this when I used extend on both dicts.

dict_a = dict.fromkeys(['x', 'y', 'z'], [])
dict_b = {'x': [], 'y': [], 'z': []}

dict_a == dict_b  # returns True
type(dict_a) == type(dict_b)  # returns True

def test_dicts(d):
    d['z'].extend([1, 2, 3])
    print(d)

test_dicts(dict_a) returns

{'x': [1, 2, 3], 'y': [1, 2, 3], 'z': [1, 2, 3]}

test_dicts(dict_b) returns

{'x': [], 'y': [], 'z': [1, 2, 3]}

Is this expected behavior? If so, why?

  • You're only ever creating *one* list object there with `[]`, which gets assigned to all keys. – deceze Feb 21 '19 at 15:17
  • Just to be clear, this isn't specific to `fromkeys` but more to the way python works, try `l = [[]] * 10` and `l[0].append(42)`. – Benoît P Feb 21 '19 at 15:26

0 Answers0