追加到列表的字典可为每个键增加价值 [英] Appending to dict of lists adds value to every key

查看:57
本文介绍了追加到列表的字典可为每个键增加价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空列表的字典,所有键都在开头声明:

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': []}

当我尝试将一个坐标对(列表 ["x1","y1"] )添加到键的一个列表中时,它会添加到所有键的列表中:

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']]}

我要找的是:

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

如何在Python 3中实现这一目标?

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.

我认为您仍然可以使用 fromkeys 来解决此问题.尝试改用dict理解.

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}

这篇关于追加到列表的字典可为每个键增加价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆