1

Let's say I have the dictionary:

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

How could I go about finding which keys have 1 (in this example, that being apple and orange)?

And how could I figure out the number of keys in this example that have the value 1 is 2?

  • 4
    Does this answer your question? [count the number of occurrences of a certain value in a dictionary in python?](https://stackoverflow.com/questions/48371856/count-the-number-of-occurrences-of-a-certain-value-in-a-dictionary-in-python) – Doodle Dee Dec 21 '19 at 08:00
  • IF you use pandas, you can do these easily like this: pd.DataFrame(fruitEaten, index=[0]).T.groupby(0).size().rename_axis(index=None) or pd.DataFrame(fruitEaten, index=[0]).T == 1 – oppressionslayer Dec 21 '19 at 08:52

2 Answers2

2

Use 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

Use Counter:

from collections import Counter

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

print(freq[1])
9mat
  • 1,194
  • 9
  • 13
0

You should use filter method like this:

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)
thisshri
  • 632
  • 8
  • 18