Search code examples
pythonlistdictionarysublist

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?


Solution

  • Using dict comprehension :

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

    output:

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