python - create a dict with unique keys and various list values from a tuple -
i have list of tuples one:
[('id1', 'text1', 0, 'info1'), ('id2', 'text2', 1, 'info2'), ('id3', 'text3', 1, 'info3'), ('id1', 'text4', 0, 'info4'), ('id4', 'text5', 1, 'info5'), ('id3', 'text6', 0, 'info6')]
i want convert dict, keeping ids keys , other values lists of tuples, expanding ones aready exist:
{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')], 'id2': [('text2', 1, 'info2')], 'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')], 'id4': [('text5', 1, 'info5')]}
right use pretty simple code:
for x in list: if x[0] not in list: list[x[0]] = [(x[1], x[2], x[3])] else: list[x[0]].append((x[1], x[2], x[3]))
i beleive there should more elegant way achieve same result, generators maybe. ideas?
a useful function appending lists inside dictionary these kind of problems dict.setdefault. can use retrieve existing list dictionary, or add empty 1 if missing, so:
data = [('id1', 'text1', 0, 'info1'), ('id2', 'text2', 1, 'info2'), ('id3', 'text3', 1, 'info3'), ('id1', 'text4', 0, 'info4'), ('id4', 'text5', 1, 'info5'), ('id3', 'text6', 0, 'info6')] x = {} tup in data: x.setdefault(tup[0], []).append(tup[1:])
result:
{'id1': [('text1', 0, 'info1'), ('text4', 0, 'info4')], 'id2': [('text2', 1, 'info2')], 'id3': [('text3', 1, 'info3'), ('text6', 0, 'info6')], 'id4': [('text5', 1, 'info5')]}
alternatively, use collections.defaultdict:
from collections import defaultdict x = defaultdict(list) tup in data: x[tup[0]].append(tup[1:])
which has similar results.
Comments
Post a Comment