Issue
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?
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()}
Answered By - Kirill Nedelev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.