77

这让我有些心痛……

我从列表中创建了一本字典

l = ['a','b','c']
d = dict.fromkeys(l, [0,0]) # initializing dictionary with [0,0] as values

d['a'] is d['b'] # returns True

如何使字典的每个值成为单独的列表?如果不遍历所有键并将它们设置为列表,这是否可能?我想修改一个列表而不更改所有其他列表。

4

4 回答 4

45

您可以使用 dict 理解:

>>> keys = ['a','b','c']
>>> value = [0, 0]
>>> {key: list(value) for key in keys}
    {'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}
于 2013-03-20T06:08:14.760 回答
40

这个答案在这里是为了向任何被他们试图用可变默认值实例化 a 的结果弄糊涂的人解释dict这种fromkeys()行为dict

考虑:

#Python 3.4.3 (default, Nov 17 2016, 01:08:31) 

# start by validating that different variables pointing to an
# empty mutable are indeed different references.
>>> l1 = []
>>> l2 = []
>>> id(l1)
140150323815176
>>> id(l2)
140150324024968

因此任何更改l1都不会影响l2,反之亦然。到目前为止,这对于任何可变的都是正确的,包括dict.

# create a new dict from an iterable of keys
>>> dict1 = dict.fromkeys(['a', 'b', 'c'], [])
>>> dict1
{'c': [], 'b': [], 'a': []}

这可能是一个方便的功能。在这里,我们为每个键分配一个默认值,该值也恰好是一个空列表。

# the dict has its own id.
>>> id(dict1)
140150327601160

# but look at the ids of the values.
>>> id(dict1['a'])
140150323816328
>>> id(dict1['b'])
140150323816328
>>> id(dict1['c'])
140150323816328

事实上,他们都使用相同的参考!改变一个就是改变所有,因为它们实际上是同一个对象!

>>> dict1['a'].append('apples')
>>> dict1
{'c': ['apples'], 'b': ['apples'], 'a': ['apples']}
>>> id(dict1['a'])
>>> 140150323816328
>>> id(dict1['b'])
140150323816328
>>> id(dict1['c'])
140150323816328

对许多人来说,这不是预期的!

现在让我们尝试将列表的显式副本用作默认值。

>>> empty_list = []
>>> id(empty_list)
140150324169864

现在创建一个带有empty_list.

>>> dict2 = dict.fromkeys(['a', 'b', 'c'], empty_list[:])
>>> id(dict2)
140150323831432
>>> id(dict2['a'])
140150327184328
>>> id(dict2['b'])
140150327184328
>>> id(dict2['c'])
140150327184328
>>> dict2['a'].append('apples')
>>> dict2
{'c': ['apples'], 'b': ['apples'], 'a': ['apples']}

还是不开心!我听到有人喊,那是因为我使用了一个空列表!

>>> not_empty_list = [0]
>>> dict3 = dict.fromkeys(['a', 'b', 'c'], not_empty_list[:])
>>> dict3
{'c': [0], 'b': [0], 'a': [0]}
>>> dict3['a'].append('apples')
>>> dict3
{'c': [0, 'apples'], 'b': [0, 'apples'], 'a': [0, 'apples']}

的默认行为fromkeys()是分配None给值。

>>> dict4 = dict.fromkeys(['a', 'b', 'c'])
>>> dict4
{'c': None, 'b': None, 'a': None}
>>> id(dict4['a'])
9901984
>>> id(dict4['b'])
9901984
>>> id(dict4['c'])
9901984

事实上,所有的值都是相同的(也是唯一的!)None。现在,让我们以无数种方式中的一种方式迭代dict并更改值。

>>> for k, _ in dict4.items():
...    dict4[k] = []

>>> dict4
{'c': [], 'b': [], 'a': []}

唔。看起来和以前一样!

>>> id(dict4['a'])
140150318876488
>>> id(dict4['b'])
140150324122824
>>> id(dict4['c'])
140150294277576
>>> dict4['a'].append('apples')
>>> dict4
>>> {'c': [], 'b': [], 'a': ['apples']}

但它们确实是不同[]的 s,在这种情况下,这是预期的结果。

于 2017-06-12T18:07:43.130 回答
12

你可以使用这个:

l = ['a', 'b', 'c']
d = dict((k, [0, 0]) for k in l)
于 2013-03-20T06:07:58.800 回答
3
l = ['a','b','c']
d = dict((i, [0, 0]) for i in l)
于 2013-03-20T06:08:37.847 回答