0

I have a dict like this:

{
    'first':{'value': 2, 'blah': 'ants'}, 
    'second':{'value': 5, 'blah': 'birds'}, 
    'third':{'value': 8, 'blah': 'cats'},
    'fourth':{'value': 10, 'blah': 'cats'}
}

I want the output to be 25 i.e(2+5+8+10)

How can I do this?

PraNisher
  • 97
  • 7
  • 3
    What have you tried so far ? Have a look at [*Iterating over dictionaries using 'for' loops*](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) if you don't know how to iterate dictionary in Python. – Alexandre B. Aug 02 '19 at 09:04
  • You iterate over the dict and add the values together. – Dschoni Aug 02 '19 at 09:07

2 Answers2

3

You can use sum() (doc) builtin function and iterate over dictionary values:

d = {
    'first':{'value': 2, 'blah': 'ants'},
    'second':{'value': 5, 'blah': 'birds'},
    'third':{'value': 8, 'blah': 'cats'},
    'fourth':{'value': 10, 'blah': 'cats'}
}

print(sum(v['value'] for v in d.values()))

OR (Thanks Gabor), if key 'value' doesn't exists to get default value 0:

print(sum(v.get('value', 0) for v in d.values()))

Prints:

25
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You can calculate by using below one,

cc={
'first':{'value': 2, 'blah': 'ants'},
'second':{'value': 5, 'blah': 'birds'},
'third':{'value': 8, 'blah': 'cats'},
'fourth':{'value': 10, 'blah': 'cats'}

}

dictionary = {}
counter = 0
sum = 0
for i in cc:
    dictionary[i] = counter
    datavalue = list(cc.values())[counter].values()[1]
    counter += 1
    sum += datavalue

print sum
Vicky
  • 819
  • 2
  • 13
  • 30