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
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.
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)]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With