ProfHase85
ProfHase85

Reputation: 12183

Group elements in list by key

Assuming I've got the following list:

mylist = [keyobj1, valobj1, valobj2, keyobj2, valobj1, valobj2, valobj3,...]

I would like to get a dict out of it containing:

mydict = {keyobj1: [valobj1, valobj2], keyobj2: [valobj1,valobj2,valobj3, ...}

Is there a library which performs this task?

Below is the rough algorithm which is to be performed (I know, looks ugly):

# convert mylist to iterator
mylist = iter(mylist)
n = mylist.next()
while True:
     try:
         if not iskey(n):
             n = mylist.next()
             value_list.append(n)
         else:
             mydict[key] = value_list
             value_list = []
             key = n
             n = mylist.next()
     except StopIteration:
         mydict[key] = value_list
         break

Upvotes: 2

Views: 129

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

I'd do it this way:

mydict = defaultdict(list)
sublist = None
for item in mylist:
    if iskey(item):
        sublist = mydict[item]
    else:
        sublist.append(item)

The only library that occurred to me to use was collections, for defaultdict.

Upvotes: 5

Related Questions