elinx elinx - 4 months ago 7
Python Question

How to convert a tuple list with duplicated keys and values into a fancy dicionary?

I have a tuple list like the code below, an identifier has multiple values(both identifier and values maybe duplicated), I thought using

dict
with a
str
as a key and a
set
as it's value would be reasonable, but how?

tuple_list = [
('id1', 123),
('id1', 123),
('id2', 123),
('id1', 456),
('id2', 456),
('id1', 789),
('id2', 789)
]


What I need is like this:
{ 'id1': {123, 456, 789}
, ... }`, my code is:

for id, val in tuple_list:
map_data[id].append(val) # error here, how to fix this?

Answer

To use a dict containing a set do it like this.

from collections import defaultdict

tuple_list = [
    ('id1', 123),
    ('id1', 123),
    ('id2', 123),
    ('id1', 456),
    ('id2', 456),
    ('id1', 789),
    ('id2', 789)
]

map_data = defaultdict(set)

for id, val in tuple_list:
    map_data[id].add(val)

print(map_data)

result

defaultdict(<type 'set'>, {'id2': set([456, 123, 789]), 'id1': set([456, 123, 789])})
Comments