0

I have the following code:

TESTS = ['C2P', 'FH', 'ACCURACY', 'DUPLICITY']
TESTING_LEVELS = ['IF', 'MF', 'MONO']
ALL_CAMERAS = ['main', 'fisheye_rectified', 'narrow', 'frontCornerLeft', 'frontCornerRight',
       'rearCornerLeft', 'rearCornerRight', 'rear']

SET_A = dict.fromkeys(TESTING_LEVELS, dict.fromkeys(TESTS, dict.fromkeys(ALL_CAMERAS, False)))
SET_B = dict.fromkeys(TESTING_LEVELS, dict.fromkeys(TESTS, dict.fromkeys(ALL_CAMERAS, False)))

For some reason, the dictionaries under SET_A and SET_B point to the same location. From the Python documentation it seems that dict.fromkeys creates new dictionaries. Why is this happening? Does it have something to do with the hashing-functions used to map the keys to the values?

Any help is much appreciated.

Elad Edri
  • 331
  • 2
  • 9
  • Python will never implicitly make a copy of an object. `SET_A` and `SET_B` are distinct objects, but they are composed of various references to the same objects. – juanpa.arrivillaga Jan 29 '18 at 18:47
  • What do you mean by " point to the same location" ? Both `SET_A is SET_B` and `id(SET_A) == id(SET_B)` return false, they are not pointing to the same location, as expected. – llllllllll Jan 29 '18 at 18:47
  • OP probably means that the nested dictionary values in SET_A and SET_B respectively refer to single dict per nesting level, which is obvious if one reads what `dict.fromkeys()` does with the 2nd argument. – Ilja Everilä Jan 29 '18 at 18:51

1 Answers1

0

They are new dicts, but the lists are references to the same list data. Take a look at copy.deepcopy ()

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45