matteo
matteo

Reputation: 4873

Get first element of sublist as dictionary key in python

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?

Upvotes: 8

Views: 6305

Answers (5)

Kelly Bundy
Kelly Bundy

Reputation: 27588

Another:

d = {k: v for k, *v in ll}

Upvotes: -1

Mike Robins
Mike Robins

Reputation: 1773

Another variation on the theme:

d = {e.pop(0): e for e in ll}

Upvotes: 2

The6thSense
The6thSense

Reputation: 8335

Using dict comprehension :

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

output:

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

Upvotes: 11

Anand S Kumar
Anand S Kumar

Reputation: 90889

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]}

Upvotes: 7

hiro protagonist
hiro protagonist

Reputation: 46849

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]}

Upvotes: 2

Related Questions