Home > Enterprise >  count of the multiple values in a python dictionary
count of the multiple values in a python dictionary

Time:08-09

I have a dictionary like the one below and I want to find out how many of the values in it are from the value entered by the user.

{'a': ['Sun', 'Jack'], 'b': ['John', 'Sun', 'Sarah'],...

Count how many 'Sun' in dictionary

Expected output: 2

CodePudding user response:

You can use sum.

dct = {'a': ['Sun'], 'b': ['John', 'Sun', 'Sarah']}
res = sum('Sun' in lst for lst in dct.values())
print(res)
# 2

CodePudding user response:

I think the most straightforward way is to go through each value of the dict

dictionary = {'a': ['Sun', 'Jack'], 'b': ['John', 'Sun', 'Sarah']}
count = 0
for key in dictionary:
  if 'Sun' in dictionary[key]:
    count  = 1
print(count)

CodePudding user response:

Chain the all values of the dictionary with itertools.chain.from_iterable, and then count with collections.Counter:

>>> from collections import Counter
>>> from itertools import chain
>>> mapping = {'a': ['Sun', 'Jack'], 'b': ['John', 'Sun', 'Sarah']}
>>> Counter(chain.from_iterable(mapping.values()))['Sun']
2

CodePudding user response:

one can also use enumerate for counting.

d = {'a': ['Sun', 'Jack'], 'b': ['John', 'Sun', 'Sarah']}

max([i for i, l in enumerate(list(d.values()), 1) if "Sun" in l])
2
  • Related