Home > front end >  Counting number of a value in a dictionary when values are a list of lists
Counting number of a value in a dictionary when values are a list of lists

Time:12-15

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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()))

CodePudding user response:

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'))
  • Related