Python count of items in a dictionary of lists

后端 未结 2 1808
面向向阳花
面向向阳花 2021-01-18 05:11

I have a dictionary of lists for which I want to add a value to a particular list... I have the following dictionary of lists.

d = {\'a\': [4,\'Adam\', 2], \         


        
2条回答
  •  一个人的身影
    2021-01-18 05:27

    collections.Counter is always good for counting things.

    >>> from collections import Counter
    >>> d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}
    >>> # create a list of only the values you want to count,
    >>> # and pass to Counter()
    >>> c = Counter([values[1] for values in d.itervalues()])
    >>> c
    Counter({'Adam': 2, 'Bill': 2, 'Bob': 1, 'John': 1, 'Joe': 1})
    

提交回复
热议问题