Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of tuples of several values into dictionary in Python

I have this list.

List1 = [(1L, 'Jack', 129L, 37L), (2L, 'Tom', 231L, 23L)]

I want to convert it into a dictionary that looks like this;

Dict1 = {'1L': [('Jack', 129L, 37L)], '2L': [('Tom', 231L, 23L)]}

I tried Dict1 = dict(List1) but got an error with something like "dictionary update sequence element #0 has length XX ..."

How can this be done in Python? I am using Python 2.7

like image 570
guagay_wk Avatar asked Jan 12 '23 02:01

guagay_wk


2 Answers

The dict constructor can work on a list of key/value pairs but not a list of arbitary-length sequences. One concise approach would be to slice each subsequence with a generator expression:

Dict1 = dict((sublist[0], sublist[1:]) for sublist in List1)

Because you're on 2.7 you could also use a dictionary comprehension:

Dict1 = {sublist[0]: sublist[1:] for sublist in List1}

There are other ways to do this, but I think these are the most Pythonic - the dict comprehension for versions that support that syntax (2.7 and later) or the generator expression for earlier versions. In both forms you're explicitly declaring the dict as having the first element of each sublist as the key and everything else as the value - dictionaries have a single value for each key, even if that value might itself have several elements.

like image 117
Peter DeGlopper Avatar answered Jan 28 '23 00:01

Peter DeGlopper


This should work:

>>> Dict1 = {}
>>> for each in List1:
...     Dict1[each[0]] = [each[1:]]

A more concise one-liner would be

>>> dict((each[0], each[1:]) for each in List1)

In both cases, the output is:

{1L: [('Jack', 129L, 37L)], 2L: [('Tom', 231L, 23L)]}
like image 38
Santosh Ghimire Avatar answered Jan 27 '23 22:01

Santosh Ghimire