Ad

How To Groupby A List?

- 1 answer

For example, if we have a list of a lot of names. How to count occurrences in a sequence? Or more exactly, how to use groupby to sort the list and count? My case, the list is not just ['a','b','c','d']. I have 60 diffenent very long strings.

Ad

Answer

itertools.groupby is a great tool for counting the numbers of occurrences in a sequence.

import itertools
name_test_random = [**a list of a lot of names**]
valdict = dict((k, len(list(g)))
           for k, g in itertools.groupby(name_test_random))
for key, val in valdict.items():
    print(key, ":", val)
Ad
source: stackoverflow.com
Ad