8

I looked but i didn't found the answer (and I'm pretty new to python).

The question is pretty simple. I have a list made of sublists:

ll
[[1,2,3], [4,5,6], [7,8,9]]

What I'm trying to do is to create a dictionary that has as key the first element of each sublist and as values the values of the coorresponding sublists, like:

d = {1:[2,3], 4:[5,6], 7:[8,9]}

How can I do that?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
matteo
  • 4,683
  • 9
  • 41
  • 77

5 Answers5

11

Using dict comprehension :

{words[0]:words[1:] for words in lst}

output:

{1: [2, 3], 4: [5, 6], 7: [8, 9]}
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65
7

Using dictionary comprehension (For Python 2.7 +) and slicing -

d = {e[0] : e[1:] for e in ll}

Demo -

>>> ll = [[1,2,3], [4,5,6], [7,8,9]]
>>> d = {e[0] : e[1:] for e in ll}
>>> d
{1: [2, 3], 4: [5, 6], 7: [8, 9]}
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

you could do it this way:

ll = [[1,2,3], [4,5,6], [7,8,9]]
dct = dict( (item[0], item[1:]) for item in ll)
# or even:   dct = { item[0]: item[1:] for item in ll }
print(dct)
# {1: [2, 3], 4: [5, 6], 7: [8, 9]}
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2

Another variation on the theme:

d = {e.pop(0): e for e in ll}
Mike Robins
  • 1,733
  • 10
  • 14
-1

Another:

d = {k: v for k, *v in ll}
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65