简体   繁体   中英

How can you print the sum of only the values of specific key in a nested dictionary [Python]?

I've been working on a project but I'm stuck. I want to get the sum of the values of a specific key nested dictionary but don't know where to start. I've tried multiple things with the dict.get(), but didn't make progres. I won't show you my whole program because that's not relevant, so I've made the concept of my program:

dictionary = {"A":4,"E":{"B":4,"C":8}}
print(dictionary.get("E", "error")) # I want 12 instead of {"B":4,"C":8}
print(dictionary.get("A", "error") # displays 4

thanks in advance

Try something like this:

dictionary = {"A":4,"E":{"B":4,"C":8}}

print(sum(dictionary.get("E", "error").values()))
print(dictionary.get("A", "error"))

Something like:

data = {"A": 4, "E": {"B": 4, "C": 8}}


def sum_it(d: dict, key: str):
    val = d.get(key)
    if not val:
        raise Exception(f'Could not find {key}')
    if isinstance(val, dict):
        return sum(val.values())
    else:
        return val  # assuming it is an int


print(sum_it(data, 'A'))
print(sum_it(data, 'E'))

output

4
12

There is no straightforward way to getting the sum of a nested dictionary. But if you are sure that it has a dictionary at the given key in that case it's simple to extract the list of the values and sum.

dictionary = {"A":4,"E":{"B":4,"C":8}}
if(isinstance(dictionary.get("Key") , int)):
  print(dictionary.get("Key"))
else:
  print(sum(dictionary["key"].values()))

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