dict.fromkeys 都指向同一个列表 [英] dict.fromkeys all point to same list
本文介绍了dict.fromkeys 都指向同一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这让我有点难过...
我从列表中创建了一个字典
l = ['a','b','c']d = dict.fromkeys(l, [0,0]) # 用 [0,0] 作为值初始化字典d['a'] 是 d['b'] # 返回真
如何使字典的每个值成为一个单独的列表?如果不迭代所有键并将它们设置为等于列表,这可能吗?我想修改一个列表而不更改所有其他列表.
解决方案
你可以使用字典理解:
<预><代码>>>>键 = ['a','b','c']>>>值 = [0, 0]>>>{key: list(value) for key in keys}{'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}This was causing me a bit of grief...
I created a dictionary from a list
l = ['a','b','c']
d = dict.fromkeys(l, [0,0]) # initializing dictionary with [0,0] as values
d['a'] is d['b'] # returns True
How can I make each value of the dictionary a seperate list? Is this possible without iterating over all keys and setting them equal to a list? I'd like to modify one list without changing all the others.
解决方案
You could use a dict comprehension:
>>> keys = ['a','b','c']
>>> value = [0, 0]
>>> {key: list(value) for key in keys}
{'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}
这篇关于dict.fromkeys 都指向同一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文