Home > Blockchain >  list of tuples to Counter or a dictionary of counts
list of tuples to Counter or a dictionary of counts

Time:11-24

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:

[(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?

CodePudding user response:

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

CodePudding user response:

You can achieve this using Dict Comprehensions, will look something like this:

x = [(k1, 400), (k1, 500), (k2, 600), (k2, 600), (k3, 600)]
dictionary = {k: v for k,v in x}
print(dictionary)

Output:

{'k1': 500, 'k2': 600, 'k3': 600}
  • Related