得到一个字典键的计数,其值大于python中的某个整数

时间:2017-05-03 01:27:16

标签: python dictionary integer

我有一本字典。键是单词,值是这些单词出现的次数。

countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}

我想知道有多少元素出现的值大于1,值大于20且值大于50。

我找到了这段代码

a = sum(1 for i in countDict if countDict.values() >= 2)

但是我得到一个错误,我猜这意味着字典中的值不能作为整数处理。

builtin.TypeError: unorderable types: dict_values() >= int()

我尝试修改上面的代码,使字典值为整数但不起作用。

a = sum(1 for i in countDict if int(countDict.values()) >= 2)

builtins.TypeError: int() argument must be a string or a number, not 'dict_values'

有什么建议吗?

5 个答案:

答案 0 :(得分:3)

你需要这个:

>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}

>>> sum(1 for i in countDict.values() if i >= 2)
5

values()会返回给定字典中所有可用值的列表,这意味着您无法将列表转换为整数。

答案 1 :(得分:3)

你可以使用collections.Counter和“分类函数”来一次性获得结果:

def classify(val):
    res = []
    if val > 1:
        res.append('> 1')
    if val > 20:
        res.append('> 20')
    if val > 50:
        res.append('> 50')
    return res

from collections import Counter

countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
Counter(classification for val in countDict.values() for classification in classify(val))
# Counter({'> 1': 5, '> 20': 2, '> 50': 1})

当然,如果您想要不同的结果,可以更改返回值或阈值。

但你实际上非常接近,你可能只是混淆了语法 - 正确的是:

a = sum(1 for i in countDict.values() if i >= 2)

因为你想迭代values()并检查每个值的条件。

你得到的是一个例外,因为

之间的比较
>>> countDict.values()
dict_values([2, 409, 2, 41, 2])

和像2这样的整数没有任何意义。

答案 2 :(得分:2)

countDict.items()countDict为您提供键值对,因此您可以写:

>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
>>> [word for word, occurrences in countDict.items() if occurrences >= 20]
['who', 'joey']

如果您只想要单词数,请使用len

>>> countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
>>> wordlist = [word for word, occurrences in countDict.items() if occurrences >= 20]
>>> len(wordlist)
2

请注意,Python变量使用小写和下划线而不是camelcase:count_dict而不是countDict。值得使用此约定以避免让自己和他人混淆。有关详细信息,请参阅PEP8

答案 3 :(得分:0)

你很亲密。您只需记住i可以通过if语句访问。我添加了所有三个示例来帮助您入门。此外,values会创建字典中所有值的列表,这不是您想要的,而是需要当前评估的值i

moreThan2 = sum(1 for i in countDict if countDict[i] >= 2)
moreThan20 = sum(1 for i in countDict if countDict[i] >= 20)
moreThan50 = sum(1 for i in countDict if countDict[i] >= 50)

答案 4 :(得分:0)

在应用歧视逻辑之前尝试使用.items()。

in -

for key, value in countDict.items():
  if value == 2: #edit for use
     print key

out -

house
boy
girl
相关问题