Victor_G
Victor_G

Reputation: 27

Counting number of a value in a dictionary when values are a list of lists

I have a dictionary where the values are a list of lists and I want to count the number of times a certain value shows up in the dictionary. I've tried something like this this:

d = { 'A': ['apple', 'banana', 'grape'],
      'B': ['cherry', 'tomato', 'apple'],
      'C': ['grape', 'kiwi', 'banana']
      }
print(list(d.values()).count('apple'))

But when I try that I get zero back

Upvotes: 1

Views: 68

Answers (4)

buran
buran

Reputation: 14273

using collections.Counter and itertools.chain()

from collections import Counter
from itertools import chain

d = { 'A': ['apple', 'banana', 'grape'],
      'B': ['cherry', 'tomato', 'apple'],
      'C': ['grape', 'kiwi', 'banana']}

cntr = Counter(chain(*d.values()))
print(cntr.get('apple'))

Upvotes: 1

Kris
Kris

Reputation: 8873

You have to count on each list, not on list of lists.

d = {'A': ['apple', 'banana', 'grape'],
     'B': ['cherry', 'tomato', 'apple'],
     'C': ['grape', 'kiwi', 'banana']
     }
# This counts on list of lists - not on each list- your appraoch
print(list(d.values()).count('apple'))

# This counts on each list - Solution
print(sum(l.count('apple') for l in d.values()))

Upvotes: 1

d.b
d.b

Reputation: 32558

d2 = {}
for d_vals in d.values():
    for el in d_vals:
        d2[el] = d2.get(el, 0) + 1
d2["apple"]
# 2

If you just need one count

sum([x.count("apple") for x in d.values()])
# 2

Upvotes: 2

user7864386
user7864386

Reputation:

Convert d.values() to a list and use collections.Counter

from collections import Counter
d_vals = []
for v in d.values():
    d_vals.extend(v)
out = Counter(d_vals)

Output:

Counter({'apple': 2,
         'banana': 2,
         'grape': 2,
         'cherry': 1,
         'tomato': 1,
         'kiwi': 1})

Then for example,

print(out['apple']) # 2

Upvotes: 1

Related Questions