Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

list of tuples to Counter or a dictionary of counts

I have a list of tuples. For each key I’d like to count the number of distinct values.

For example,

Given the following list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(k1, 400), (k1, 500), (k2, 600), (k2, 600), (k3, 600)]

I’d like to produce the following:

{k1: 2, k2: 1, k3: 1}

explanation:

k1 has two values (400, 500). k2 has only one value (600)

What’s the Pythonic way to do that?

>Solution :

from collections import defaultdict

list_of_tuples = [
    ("k1", 400),
    ("k1", 500),
    ("k2", 600),
    ("k2", 600),
    ("k3", 600),
]

dict_of_sets = defaultdict(set)

for key, value in list_of_tuples:
    dict_of_sets[key].add(value)

result = {key: len(value) for key, value in dict_of_sets.items()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading