-2

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?
Elinx
  • 1,196
  • 12
  • 20
  • 1
    Possible duplicate of [Python group by](http://stackoverflow.com/questions/3749512/python-group-by) or [How do I use Python's itertools.groupby()?](http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertools-groupby) – TessellatingHeckler Aug 04 '16 at 04:22

2 Answers2

1

You can use setdefaultdict:

map_data = {}
for id, val in tuple_list:
    map_data.setdefault(id,set()).add(val)
DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
1

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])})
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61