-1

My code of creating a nested dict from 'keys' and then updating one of the elements:

keys = ["a", "b", "c"]

d = dict.fromkeys(keys, {'foo':0, 'bar':[]})

d["a"]["bar"].append("x")

print(d)

I would expect that the resulting dict be the following (only updating 'bar' under key 'a'):

{
  "a": {
    "foo": 0,
    "bar": ["x"]
  },
  "b": {
    "foo": 0,
    "bar": []
  },
  "c": {
    "foo": 0,
    "bar": []
  }
}

But instead I'm getting

{
  "a": {
    "foo": 0,
    "bar": ["x"]
  },
  "b": {
    "foo": 0,
    "bar": ["x"]
  },
  "c": {
    "foo": 0,
    "bar": ["x"]
  }
}
maasir
  • 3
  • 1
  • 2
  • `dict.fromkeys()` is generally useless with a mutable value, because that value will be shared by every key in the dict. – jasonharper Aug 12 '22 at 15:08
  • The empty list object in each "bar" must be pointing to the same memory address. This issue crops up when supplying mutable values like lists as function arguments. A dict-comprehension will work better here, as @funnydman shows in their answer – Joe Carboni Aug 12 '22 at 15:10

1 Answers1

0

With your approach, you'll get the same objects for every key. Try this instead:

keys = ["a", "b", "c"]


result = {k: {'foo': 0, 'bar': []} for k in keys}
result['a']['bar'].append('x')
print(result)

Output:

{'a': {'foo': 0, 'bar': ['x']}, 'b': {'foo': 0, 'bar': []}, 'c': {'foo': 0, 'bar': []}}
funnydman
  • 9,083
  • 4
  • 40
  • 55