Create dict with unique keys and different list values ​​from tuple

I have a list of tuples like this:

[('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 to convert it to a dict, keeping IDs as keys and all other values ​​as lists of tuples, expanding on those that exist:

{'id1': [('text1', 0, 'info1'),
         ('text4', 0, 'info4')],
 'id2': [('text2', 1, 'info2')],
 'id3': [('text3', 1, 'info3'),
         ('text6', 0, 'info6')],
 'id4': [('text5', 1, 'info5')]}

      

Right now I am using 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 believe there must be a more elegant way to achieve the same result, perhaps with generators. Any ideas?

+3


source to share


1 answer


A useful method for adding to lists contained in a dictionary for solving such problems is dict.setdefault . You can use it to extract an existing list from the dictionary, or add an empty one if it is missing, for example:

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 = {}
for 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, you can use collection.defaultdict :

from collections import defaultdict
x = defaultdict(list)
for tup in data:
    x[tup[0]].append(tup[1:])

      

which has similar results.

+6


source







All Articles