-2

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?

IsaacLevon
  • 2,260
  • 4
  • 41
  • 83
  • 1
    What you have tried and where do you get stuck? Even not very Pythonic. – Daniel Hao Nov 23 '21 at 12:23
  • 1
    Does this answer your question? [Counting the amount of occurrences in a list of tuples](https://stackoverflow.com/questions/16013485/counting-the-amount-of-occurrences-in-a-list-of-tuples) – Luuk Nov 23 '21 at 12:31

2 Answers2

1
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()}
  • Not sure this is considered more `Pythonic`. Find out the link provided by @Luuk by `Counter` is more Pythonic. – Daniel Hao Nov 23 '21 at 13:12
0

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}