Christian Kilian
Christian Kilian

Reputation: 35

Python sum values within nested dictionaries

For my first actual project, I am attempting to create a simple incremental game that runs in the Python IDLE. I have come across an issue where I need to get the sum of multiple values within nested dictionaries and am stuck.

Here is the dictionary that I am working with:

clickers = {
'': None,
'wooden_sword': {
    'owned': 5,
    'power': 1,
    'price': 5,
    },
'iron_sword': {
    'owned': 10,
    'power': 2.5,
    'price': 10,
    },
}

I am wondering if it would be possible to get the sum of just the owned values and save it to a variable.

The key wooden_sword's owned value is equal to 5, and the key iron_sword's owned value is equal to 10, I would like to sum those values and save them to a variable equal to their solution.

Upvotes: 1

Views: 90

Answers (3)

blhsing
blhsing

Reputation: 106455

You can use the sum function with a generator expression:

sum(d['owned'] for d in clickers.values() if d)

This returns:

15

Upvotes: 1

Sociopath
Sociopath

Reputation: 13401

I think you need:

sum_ = 0
for k,v in clickers.items():
    if v:        # to ignore None 
        try:     # this to avoid key error
            sum_ += v['owned']
        except:
            pass
print(sum_)

Upvotes: 1

taurus05
taurus05

Reputation: 2546

It can be done this way.

total = 0
for key ,value in clickers.items():
  if value and 'owned' in value.keys():
    total += value['owned']
print(total)

Upvotes: 1

Related Questions