Adding to the list type adds value to each key.

I have a dictionary of empty lists with all the 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 (list ["x1", "y1"]) to one of the key lists, it instead adds all the key lists:

>>> d["k1"].append(["x1", "y1"])
>>> d
{'k1': [['x1', 'y1']], 'k2': [['x1', 'y1']], 'k3': [['x1', 'y1']]}

I was looking for:

>>> d
{'k1': [['x1', 'y1']], 'k3': [], 'k1': []}

How can I achieve this in Python 3?

+4
source share
3 answers

It appears that each of these lists is actually a link to a single list. Adding to one of them is added to all of them.

I do not think you can get around this by continuing to use fromkeys. Try using dict comprehension instead.

d = {k: [] for k in keys}
+3
source

fromkeys - , , . , , python None . 2d- :

>>> d = dict.fromkeys(keys)
>>> d["k1"] = [["x1", "y1"]]
>>> d
{'k3': None, 'k2': None, 'k1': [['x1', 'y1']]}

python fromkeys:

@classmethod
def fromkeys(cls, iterable, value=None):
    d = cls()
    for key in iterable:
        d[key] = value
    return d
+3

:

d = {k: [] for k in keys}

dict.fromkeys() , .

, id :

>>> d = dict.fromkeys(keys,[])
>>> [id(v) for v in d.values()]
[4413495432, 4413495432, 4413495432]

id , , .

+2

Source: https://habr.com/ru/post/1626587/


All Articles