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?
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.
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.
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.
Using dict comprehension :
{words[0]:words[1:] for words in lst}
output:
{1: [2, 3], 4: [5, 6], 7: [8, 9]}
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