如何在 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']}
这是有效的
data = {0:[],1:[]}
data[1].append('hello')
print data
实际和预期结果:{0: [], 1: ['hello']}
为什么 fromkeys
方法没有按预期工作?
Why is the fromkeys
method not working as expected?
推荐答案
将 []
作为第二个参数传递给 dict.fromkeys()
给出了一个相当无用的结果 - 所有字典中的值将是 same 列表对象.
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 中,您可以使用
In earlier versions of Python, you can use
data = dict((k, []) for k in range(2))
这篇关于如何在 Python 中初始化空列表字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!