简体   繁体   中英

Using a for loop Calculate the sum of the values in this dictionary and do not use sum() function

Using a for loop Calculate the sum of the values in this dictionary and do not use sum() function?

Dictionary = {"001": {"a" : [1, 5, 6], "b" : [2, 8, 9] }, "002": {"c" : [6.89, 5.67, 1.24], "d" : [9.32, 6, 78] }}

Ive tried to answer this in many methods but i always get this error:

TypeError: unsupported operand type(s) for +: 'int' and 'dict'

Thank you !

Use a nested loop according to the data structure:

total = 0

for dct in Dictionary.values():  # the outermost dict's values are dicts again ...
    for lst in dct.values():     # ... whose values are lists ...
        for num in lst:          # ... whose elements are addable numbers
            total += num

total
# 138.12

I think you was trying to make a sum the dictionary with the operand + Instead you need to get every single number inside of the list (remind that the list is inside of a dictionary and this dictionary is inside of another) So i make a for loop:

Dictionary = {"001": {"a": [1, 5, 6], "b": [2, 8, 9]}, "002": {"c": [6.89, 5.67, 1.24], "d": [9.32, 6, 78]}}
for c in range(0, len(Dictionary['001'])):
    l1 = Dictionary['001']['a']
    l2 = Dictionary['001']['b']
    som1 = l1[c] + l2[c]
for c in range(0, len(Dictionary['002'])):
    l1 = Dictionary['002']['c']
    l2 = Dictionary['002']['d']
    som2 = l1[c] + l2[c]
somt = som1 + som2
print(somt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM