为什么使用fromkeys初始化列表字典会影响列表的追加方式 [英] why does initialize a dictionary of lists using fromkeys affect how the list appends

查看:54
本文介绍了为什么使用fromkeys初始化列表字典会影响列表的追加方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用不同的方法创建列表字典

Creating a dict of lists using different methods

d1 = {'foo':[],'bar':[]}
d2 = dict.fromkeys(['foo','bar'],[])

产生两个相同的格言.

print(d1==d2,d1,d2)

True {'foo': [], 'bar': []} {'foo': [], 'bar': []}

但是,将值附加到列表中

However, appending values to the lists

d1['foo'].append('a')
d2['foo'].append('a')

d1['foo'].append(2)
d2['foo'].append(2)

产生两个不同的指示.为什么字典的初始化方法会影响列表附加行为?

yields two different dicts. Why does the initialization method of a dict affect the list append behaviour?

print(d1==d2,d1,d2)

False {'foo': ['a', 2], 'bar': []} {'foo': ['a', 2], 'bar': ['a', 2]}

在fromkeys之后,python也会将list append语句应用于所有其他键.

After fromkeys, python applies list append statements to all other keys too.

推荐答案

使用fromkeys时,正在发生的事情是正在创建字典,并且其所有键都具有与其值相同的对象.

When you use fromkeys, what is happening is the dictionary is being created, and all its keys have the same object as their value.

这意味着d2["foo"]d2["bar"]都引用相同的对象.它是相同对象,而不仅仅是相同对象.因此,通过一个键进行修改会在所有其他键之间进行更改.

What this means is that both d2["foo"] and d2["bar"] refer to the same object. It is the same object, not just an identical one. Therefore, modifying it via one key changes it across all other keys.

如果使用自定义对象,这会更加引人注目:

This is a lot more noticeable if you use a custom object:

class MyClass:
    def __init__(self):
        pass

a = MyClass()
d = dict.fromkeys(["foo", "bar"], a)

打印d会产生以下输出:

{'foo': <__main__.MyClass object at 0x0000000004699AC8>, 'bar': <__main__.MyClass object at 0x0000000004699AC8>}

请注意内存地址如何相同,因为它是同一对象.

Notice how the memory addresses are the same, because it is the same object.

但是,在d1中,您没有将相同的对象分配给两个键.而是分配两个单独的相同(空列表).因此,修改一个不会更改另一个.

In d1 however, you do not assign the same object to both keys. Rather, you assign two separate identical ones (empty lists). Therefore modifying one does not change the other.

这篇关于为什么使用fromkeys初始化列表字典会影响列表的追加方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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