简体   繁体   English

Python字典初始化?

[英]Python dictionary initialization?

I am not sure if this is a bug or a feature. 我不确定这是一个错误还是一个功能。 I have a dictionary to be initialized with empty lists. 我有一个用空列表初始化的字典。

Lets say 让我们说

keys =['one','two','three']
sets = dict.fromkeys(keys,[])

What I observed is if you append any item to any of the lists all the lists are modified. 我观察到的是,如果您将任何项目附加到任何列表中,则会修改所有列表。

sets = dict.fromkeys(['one','two','three'],[])
sets['one'].append(1)

sets

{'three': [1],'two': [1], 'one': [1]}

But when I do it manually using loop, 但是当我手动使用循环时,

for key in keys:
      sets[key] = []
sets['one'].append(1)

sets

{'three': [], 'two': [], 'one': [1]}

I would think the second behavior should be the default. 我认为第二种行为应该是默认行为。

This is how things work in Python. 这就是Python中的工作方式。

When you use fromkeys() in this manner, you end with three references to the same list. 以这种方式使用fromkeys()时,最后fromkeys()三个对同一列表的引用。 When you change one list, all three appear to change. 当您更改一个列表时,所有三个列表都会发生变化。

The same behaviour can also be seen here: 在这里也可以看到相同的行为:

In [2]: l = [[]] * 3

In [3]: l
Out[3]: [[], [], []]

In [4]: l[0].append('one')

In [5]: l
Out[5]: [['one'], ['one'], ['one']]

Again, the three lists are in fact three references to the same list: 同样,这三个列表实际上是对同一列表的三个引用:

In [6]: map(id, l)
Out[6]: [18459824, 18459824, 18459824]

(notice how they have the same id) (注意他们如何拥有相同的id)

Other answers covered the 'Why', so here's the how. 其他答案涵盖了“为什么”,所以这里是如何。

You should use a comprehension to create your desired dictionary: 您应该使用理解来创建所需的字典:

>>> keys = ['one','two','three']
>>> sets = { x: [] for x in keys }
>>> sets['one'].append(1)
>>> sets
{'three': [], 'two': [], 'one': [1]}

For Python 2.6 and below, the dictionary comprehension can be replaced with: 对于Python 2.6及更低版本,字典理解可以替换为:

>>> sets = dict( ((x,[]) for x in keys) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM