如何在Python中初始化一个空列表的字典? [英] How do I initialize a dictionary of empty lists in Python?
问题描述
我以编程方式创建列表字典的尝试未能让我单独处理字典键。每当我创建列表的字典并尝试附加到一个键时,它们都被更新。这是一个非常简单的测试用例:
My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here's a very simple test case:
data = {}
data = data.fromkeys(range(2),[])
data[1].append('hello')
print data
实际结果: {0:['hello'],1:['hello']}
预期结果: {0:[],1:['hello']}
/ p>
Here's what works
data = {0:[],1:[]}
data[1].append('hello')
print data
实际和预期结果: {0: [],1:['hello']}
为什么 fromkeys
方法不按预期方式工作
Why is the fromkeys
method not working as expected?
推荐答案
将 []
作为第二个参数到 dict.fromkeys()
给出一个相当无用的结果 - 字典中的所有值都将是相同的列表对象。
Passing []
as second argument to dict.fromkeys()
gives a rather useless result – all values in the dictionary will be the same list object.
在Python 2.7或更高版本中,您可以使用代码理解:
In Python 2.7 or above, you can use a dicitonary comprehension instead:
data = {k: [] for k in range(2)}
在早期版本的Python中,可以使用范围(2)中的k的
In earlier versions of Python, you can use
data = dict((k, []) for k in range(2))
这篇关于如何在Python中初始化一个空列表的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!