Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to dict of lists adds value to every key [duplicate]

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?

like image 681
user1717828 Avatar asked Jan 29 '16 20:01

user1717828


2 Answers

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}
like image 62
Kevin Avatar answered Oct 15 '22 09:10

Kevin


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.

like image 29
Mike Müller Avatar answered Oct 15 '22 09:10

Mike Müller