1

Why does my command add the new value "test" to every list in my dictionary and not only to the one corresponding to key "key1"?

In:

# Create list of entries
list_f = ["key1", "key2"]

# Create dictionary out of list
dic_f = dict.fromkeys(list_f, [])

# Only append "test" as value to the key "key1"
dic_f["key1"].append("test")
dic_f

Out:

{'key1': ['test'],
 'key2': ['test']}

Desired output:

{'key1': ['test'],
 'key2': []}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
zimon
  • 77
  • 6
  • 1
    Note: >95% of the time, you don't want to preinitialize a `dict` with a specified set of keys. You just want to use `collections.defaultdict`. In this case, `collections.defaultdict(list)` would do the trick; it won't have a `'key2'` until you look it up, but as soon as you do, it will autovivify it with a fresh new `list`. – ShadowRanger Jun 07 '22 at 14:41

1 Answers1

1

I believe that happens sinse all of the the values in the dictionary are the same list,

What I mean by that is , every value in you dictionary points to the same empty list in the memory , so when you change one list all of the change since all of them are the same list

list_f = ["key1", "key2"]

# Create dictionary out of list

dic_f = {}
for key in list_f:
    dic_f[key]=[]

# Only append "test" as value to the key "key1"
dic_f["key1"].append("test")
print(dic_f)

This should do the trick :)

Ohad Sharet
  • 1,097
  • 9
  • 15