仅当键等于或大于 x 时才对字典的值求和

时间:2021-03-29 07:26:48

标签: python-3.x dictionary

给定一个包含键和值的字典,我想根据键值对值求和。例如,{1:10, 2:20, 3:30, 4:40, 5:50, 6:60},并且仅当键中的值等于或大于 2 时才对值求和,输出为 200

x =2
    count = 0
    for key, value in dictionary.items():
        while key == x:
            count += 1[value]

我的输出是 none,我不知道我错过了什么。

3 个答案:

答案 0 :(得分:0)

试试这个。您迭代字典项的方式是正确的,但在循环内部,您需要检查当前键是否大于或等于您所需的键。只有这样,您才应该使用与该键对应的值增加计数,该值可以通过这种方式检索 - dictionary[key] 或者您可以简单地添加像 count+=value

这样的值
dictionary = {1:10, 2:20, 3:30, 4:40, 5:50, 6:60}
x=2
count = 0
for key,value in dictionary.items():
    if key>=x:
        count += dictionary[key]
print(count)

答案 1 :(得分:0)

  1. 您的代码不完整,无法按原样运行,因此很难推测为什么会得到 None 的输出。

  2. 在您的要求中,您提到“等于或大于 2”,但您的代码具有“key == x”。这应该是“key >= x”。

  3. 在你的 for 循环中你有一段时间。修复其他问题会导致无限循环。你想要一个如果,而不是一会儿。

修复这些问题并做出一两个假设,您的代码将是:

x = 2
count = 0
for key, value in dictionary.items():
    if key >= x:
        count += value

或者,您可以用一行代码编写它:

sum ( v for k, v in dictionary.items() if k >= x )

答案 2 :(得分:0)

我相信你只需要做如下:

count = 0
for key, value in dictionary.items():
    if key >= n:
        count += value