【发布时间】: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