Florent
Florent

Reputation: 1938

How to select common keys of dictionaries in Python and sum values?

I have a list of nested dictionaries and I would like to select the key:value pairs where key=value and sum all values. How could I do that with a single line of code ?

[{'default': {'AA': {'quantity': 0.05215832, 'value': 2940.4440669952},
              'BB': {'quantity': 493.96434168, 'value': 888.9823555432}},
 'basic': {'CC': {'quantity': 911.84309821, 'value': 911.84309821}},
 'expert': {'DD': {'quantity': 0.00833, 'value': 0.036579529000000006},
          'AA': {'quantity': 0.000823, 'value': 0.303896042},
          'RR': {'quantity': 0.000166, 'value': 0.0035026000000000002},
          'FF': {'quantity': 0.00183, 'value': 0.057991785}}}]

I can select keys with:

[[d[i].keys() for i in [k for k, v in d.items()]]]

But I'm unable to go further.

Upvotes: 0

Views: 111

Answers (2)

M-Chen-3
M-Chen-3

Reputation: 2054

I believe this is what you're looking for.

lst = [{'default': {'AA': {'quantity': 0.05215832, 'value': 2940.4440669952},
              'BB': {'quantity': 493.96434168, 'value': 888.9823555432}},
 'basic': {'CC': {'quantity': 911.84309821, 'value': 911.84309821}},
 'expert': {'DD': {'quantity': 0.00833, 'value': 0.036579529000000006},
          'AA': {'quantity': 0.000823, 'value': 0.303896042},
          'RR': {'quantity': 0.000166, 'value': 0.0035026000000000002},
          'FF': {'quantity': 0.00183, 'value': 0.057991785}}}]

lst_sum = sum(value['value'] for key in lst[0].keys() for value in lst[0][key].values())
print(lst_sum)
# Prints 4741.6714907044

This executes a list comprehension, then sums up all of the values. It first iterates through each level ('default', 'basic', and 'expert') then iterates through each letter pair of it ('AA', 'BB', etc).

Upvotes: 1

Mathieu
Mathieu

Reputation: 5756

You could do:

input_nested_dict = {'AA': {'quantity': 0.05215832, 'value': 2940.4440669952},
                     'BB': {'quantity': 493.96434168, 'value': 888.9823555432}}
    
sum([input_nested_dict[key]['value'] for key in input_nested_dict.keys()])

I assumed based on the selection key code snipped you gave that you work on a per dictionary basis and not on the entire list at once.

You can remove the brackets to have a generator instead of a list comprehension:

sum(input_nested_dict[key]['value'] for key in input_nested_dict.keys())

Upvotes: 0

Related Questions