Home > database >  Adding sum of the nested dictionary values using keys from the list
Adding sum of the nested dictionary values using keys from the list

Time:12-20

I was creating a war game and I have this dictionary of weapons and the damage they do on another type of troops.

also, I have a list which has the keys from the dictionary stored in it.

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'] 

I need to get this output:

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

I tried this :

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

CodePudding user response:

You can use collections.Counter:

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

If you don't want to use collections library, you can also do:

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

Output:

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

CodePudding user response:

Without having to import anything. You can just map the dictionary with two loops.

out = {'air': 0, 'ground': 0, 'human': 0}

for weapon in inv:
    for k, v in weapon_specs[weapon].items():
        out[k]  = v

print(out)

Output:

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

CodePudding user response:

First take a subset of your dictionary according to your list.
Then use 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()))

Result

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