如何在嵌套字典[Python]中仅打印特定键的值之和?

如何在嵌套字典[Python]中仅打印特定键的值之和?,python,dictionary,nested,Python,Dictionary,Nested,我一直在做一个项目,但我被卡住了。我想获取特定键嵌套字典的值之和,但不知道从哪里开始。我用dict.get()尝试了多种方法,但没有取得任何进展。我不会向您展示我的整个计划,因为这不相关,所以我提出了我计划的概念: dictionary = {"A":4,"E":{"B":4,"C":8}} print(dictionary.get("E", "error")) # I wan

我一直在做一个项目,但我被卡住了。我想获取特定键嵌套字典的值之和,但不知道从哪里开始。我用dict.get()尝试了多种方法,但没有取得任何进展。我不会向您展示我的整个计划,因为这不相关,所以我提出了我计划的概念:

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

提前感谢

尝试以下方法:

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

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

试着这样做:

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

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

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'))
输出

4
12
比如:

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'))
输出

4
12

没有直接的方法可以得到嵌套字典的和。但如果您确定在这种情况下,它在给定的键处有一个字典,那么提取值和和的列表就很简单了

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

没有直接的方法可以得到嵌套字典的和。但如果您确定在这种情况下,它在给定的键处有一个字典,那么提取值和和的列表就很简单了

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

谢谢你的帮助谢谢你的帮助非常感谢非常感谢