使用列表中的键添加嵌套字典值的总和



我正在创建一个战争游戏,我有这本武器字典,以及它们对另一种类型的部队造成的伤害。

此外,我有一个列表,其中存储了字典中的密钥。

weapon_specs = {
'rifle': {'air': 1, 'ground': 2, 'human': 5},
'pistol': {'air': 0, 'ground': 1, 'human': 3},
'rpg': {'air': 5, 'ground': 5, 'human': 3},
'warhead': {'air': 10, 'ground': 10, 'human': 10},
'machine gun': {'air': 3, 'ground': 3, 'human': 10}
}
inv = ['rifle', 'machine gun', 'pistol'] 

我需要得到这个输出:

{'air': 4, 'ground': 6, 'human': 18}

我试过这个:

for i in weapon_specs:
for k in inv:
if i == k:
list.update(weapon_specs[k])

您可以使用collections.Counter:

from collections import Counter
count = Counter()
for counter in [weapon_specs[weapon] for weapon in inv]:
count += counter
out = dict(count)

如果你不想使用collections库,你也可以做:

out = {}
for weapon in inv:
for k,v in weapon_specs[weapon].items():
out[k] = out.get(k, 0) + v

输出:

{'air': 4, 'ground': 6, 'human': 18}

无需导入任何内容。你可以把字典映射成两个循环。

out = {'air': 0, 'ground': 0, 'human': 0}
for weapon in inv:
for k, v in weapon_specs[weapon].items():
out[k] += v
print(out)

输出:

{'air': 4, 'ground': 6, 'human': 18}

使用集合中的计数器添加字典值,并引用inv

from collections import Counter
weapon_specs = {'rifle': {'air': 1, 'ground': 2, 'human': 5},'pistol': {'air': 0, 'ground': 1, 'human': 3},'rpg': {'air': 5, 'ground': 5, 'human': 3},'warhead': {'air': 10, 'ground': 10, 'human': 10},'machine gun': {'air': 3, 'ground': 3, 'human': 10}}
inv = ['riffle', 'machine gun', 'pistol']
summation = Counter()
for category, values in weapon_specs.items():
if category in inv:
summation.update(values)
summation = dict(summation)
print(summation)

输出:

{'air': 4, 'ground': 6, 'human': 18}

首先根据列表获取字典的子集
然后使用Counter

from collections import Counter
subset = {k: weapon_specs[k] for k in inv}
out = dict(sum((Counter(d) for d in subset.values()), Counter()))

结果

{'air': 4, 'ground': 6, 'human': 18}

最新更新