【问题标题】:How can I find the number of keys that correlate to a value in python? [duplicate]如何找到与 python 中的值相关的键的数量? [复制]
【发布时间】:2020-04-13 12:19:43
【问题描述】:

假设我有字典:

fruitEaten = {"apple": 1, "orange": 1, "tomato": 2}

我怎样才能找到哪些键有 1(在这个例子中,是苹果和橙色)?

在这个例子中,我如何计算出值为 1 的键的数量是 2?

【问题讨论】:

标签: python dictionary key


【解决方案1】:

使用defaultdict

from collections import defaultdict

fruitEaten = {"apple": 1, "orange": 1, "tomato": 2}

freq = defaultdict(int)
for v in fruitEaten.values():
    freq[v] += 1

print(freq[1])

#2

使用计数器:

from collections import Counter

fruitEaten = {"apple": 1, "orange": 1, "tomato": 2}
freq = Counter(fruitEaten.values())

print(freq[1])

【讨论】:

    【解决方案2】:

    你应该使用这样的过滤方法:

    fruitEaten = {"apple": 1, "orange": 1, "tomato": 2}
    
    # find fruits with value 1
    fruits = list(filter(lambda fruit: fruitEaten[fruit] == 1, fruitEaten))
    
    # To get the count of fruits with value one
    len(fruits)
    

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 2021-02-19
      • 2018-03-05
      • 2023-01-26
      • 2021-04-19
      • 2017-07-01
      • 2020-11-13
      • 2021-12-26
      相关资源
      最近更新 更多