I have a dictionary of empty lists with all keys declared at the beginning:
>>> keys = ["k1", "k2", "k3"]
>>> d = dict.fromkeys(keys, [])
>>> d
{'k2': [], 'k3': [], 'k1': []}
When I try to add a coordinate pair (the list ["x1", "y1"]
) to one of the key's lists, it instead adds to all the keys' lists:
>>> d["k1"].append(["x1", "y1"])
>>> d
{'k1': [['x1', 'y1']], 'k2': [['x1', 'y1']], 'k3': [['x1', 'y1']]}
What I was looking for was:
>>> d
{'k1': [['x1', 'y1']], 'k3': [], 'k1': []}
How can I achieve this in Python 3?
Looks like each of those lists is actually a reference to a single list. Appending to one of them appends to all of them.
I don't think you can work around this while still using fromkeys
. Try using a dict comprehension instead.
d = {k: [] for k in keys}
Create your dictionary like this:
d = {k: [] for k in keys}
dict.fromkeys()
puts a reference to the same list as value for all keys into the dictionary.
You can visualize this by looking at the id
of your values:
>>> d = dict.fromkeys(keys,[])
>>> [id(v) for v in d.values()]
[4413495432, 4413495432, 4413495432]
Because the id
uniquely identifies an object, this means you have the same object three times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With