将值附加到字典中的一个列表 将值附加到字典中的所有列表 [英] Append value to one list in dictionary appends value to all lists in dictionary

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

问题描述

问题

我正在通过以下方式创建一个空列表作为值的字典.

<预><代码>>>>words = dict.fromkeys(['coach', 'we', 'be'], [])

字典是这样的.

<预><代码>>>>字{'教练':[],'是':[],'我们':[]}

当我将一个值附加到一个列表时,该值将附加到所有列表中,如本例所示.

<预><代码>>>>words['coach'].append('test'){'coach': ['test'], 'be': ['test'], 'we': ['test']}

问题

我的问题有两个部分.首先,为什么会发生这种情况?其次,我能做些什么?也就是说,如何将一个值附加到一个列表中?

我想象在创建字典时,我让所有列表都指向同一个对象.但我不明白这是怎么回事,因为当我在字典创建中输入 0 而不是 [] 然后添加值而不是附加它们时,这些值的行为不同如果它们指向不同的对象.

我将不胜感激任何输入.提前谢谢你!

解决方案

dict.fromkeys 对所有值使用相同对象,在本例中为 mutable list... 这意味着,所有键共享同一个空列表... 当你尝试将 .append 附加到一个列表的值时,更改对对象就地进行,因此所有引用它的人都可以看到对它的更改.

如果你使用了一个 dict-comp,例如: {k:[] for k in ['could', 'we', 'be']} 每个 [] 是一个不同的空列表,因此每个键值都是唯一的,并且按预期工作.

关于使用 dict.fromkeys(['a', 'b', 'c'], 0) 0不可变的 对象因此不受该问题的影响,因为对它的更改会导致新对象,而不是对不同名称(在这种情况下 - 不同键的值)可能共享的底层对象进行更改.

The Problem

I am creating a dictionary with empty lists as values in the following way.

>>> words = dict.fromkeys(['coach', 'we', 'be'], [])

The dictionary looks like this.

>>> words
{'coach': [], 'be': [], 'we': []}

When I append a value to one list, the value is appended to all of them as in this example.

>>> words['coach'].append('test')
{'coach': ['test'], 'be': ['test'], 'we': ['test']}

The Question

My question has two parts. First, why is this happening? Second, what can I do about it? That is, how can I append a value to only one list?

I imagine that in creating the dictionary, I made all lists point to the same object. But I don't understand how that can be because when I input 0 instead of [] in dictionary creation and then add values instead of append them, the values behave differently as if they point to distinct objects.

I would appreciate any input. Thank you in advance!

解决方案

dict.fromkeys uses the same object for all values, in this case a mutable list... That means, all keys share the same empty list... When you try to .append to the value of one list, the changes are made in-place to the object, so changes to it are visible by all that reference it.

If instead you used a dict-comp, eg: {k:[] for k in ['could', 'we', 'be']} each [] is a different empty list and so would be unique for each key value and work as expected.

In regards to using dict.fromkeys(['a', 'b', 'c'], 0) the 0 is an immutable object thus isn't subject to that gotcha as changes to it result in new objects, not a change to the underlying object which different names (in this case - the values of the different keys) may share.

这篇关于将值附加到字典中的一个列表 将值附加到字典中的所有列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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