Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 650
matteo Avatar asked Sep 16 '15 09:09

matteo


People also ask

How will you get the first value in a dictionary in Python?

Method #1 : Using list() + keys() The combination of the above methods can be used to perform this particular task. In this, we just convert the entire dictionaries' keys extracted by keys() into a list and just access the first key.

How do you access the elements of a sub list in Python?

Using zip and * The * allows us to unpack the sublists and give access to individual elements of the sublist. So in this case we will use * and access the element at index 0 from each element. Then we finally zip the result to get a list of the first element from the sublists.

How do you return the first value in a dictionary?

Use next() to get the first key value in a dictionary Call iter(object) with the view object from step 1 as object to return an iterator of the values. Call next(iterator) with the iterator from step 2 as iterator to return the first value from the iterator.


1 Answers

Using dict comprehension :

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

output:

{1: [2, 3], 4: [5, 6], 7: [8, 9]}
like image 182
The6thSense Avatar answered Oct 21 '22 06:10

The6thSense