【问题标题】:Python list of dictionaries incrementation error [duplicate]Python字典列表增量错误[重复]
【发布时间】:2018-12-10 23:15:24
【问题描述】:

Python 3.6

我有一个字典列表 -

houses = ['a', 'b', 'c']
rarity_values = {'Common':0,'uncommon':0}
rarity = {}.fromkeys([i for i in houses],rarity_values) # creates dictionary of id

print(rarity)
# {'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}

我正在浏览某个文档,我想计算每个house 中常见事情发生的次数。因此,如果我看到两个 Commons 代表 house a 和 1 个不常见的房子 b 我得到结果

# {'a': {'Common': 2, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 1}, 'c': {'Common': 0, 'uncommon': 0}}

但是,我注意到,当我为任何一个 house 增加 Common 的值时,它会为所有这些增加它。

print('a (before increment)',rarity['a']['Common'])
print('b (before increment)',rarity['b']['Common'])
rarity['b']['Common'] += 1
print('a (after increment)',rarity['a']['Common'])
print('b (after increment)',rarity['b']['Common'])

产生输出

a (before increment) 0
b (before increment) 0
a (after increment) 1
b (after increment) 1

而不是

a (before increment) 0
b (before increment) 0
a (after increment) 0
b (after increment) 1

因为我只将 b 增加了 1。

或者为了看得更清楚

{'a': {'Common': 1, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 1, 'uncommon': 0}}

应该是的

{'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}

有谁知道我做错了什么?我应该以不同的方式嵌套吗?

谢谢

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你应该使用字典理解。

    for i in houses:
        rarity[i] = dict(rarity_values)
    

    在您的原始代码中,您将rarity_values 的同一实例链接到每个键“a”和“b”

    【讨论】:

    • 您可能正在制作一个副本,但只有一个副本,而不是每个键一个。所有键的值仍然共享相同的字典。
    • 你说得很好
    • 当我使用dict(rarity_values) 而不是rarity_values 时,我得到了相同的输出。
    • 我已经更新了答案
    猜你喜欢
    • 2013-02-09
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多