Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting List to Dict

When I had a list that was in format of

list1 = [[James,24],[Ryan,21],[Tim,32]...etc] 

I could use

dic1 =dict(list1)

However now lets say I have multiple values such as

list1 = [[James,24,Canada,Blue,Tall],[Ryan,21,U.S.,Green,Short
[Tim,32,Mexico,Yellow,Average]...etc]

I have no idea how to go about creating a dict so that it would show the first name as the key and the following values as the value.

Thanks in advance

like image 675
Ravash Jalil Avatar asked Nov 30 '22 18:11

Ravash Jalil


2 Answers

Loop through the entries of your list and add them to the dictionary:

for entry in list:
    dict[entry[0]]=entry[1:]
like image 20
lodo Avatar answered Dec 04 '22 09:12

lodo


You can use a dict comprehension and slicing :

>>> list1 = [['James','24','Canada','Blue','Tall'],['Ryan','21','U.S.','Green','Short']]
>>> {i[0]:i[1:] for i in list1}
{'James': ['24', 'Canada', 'Blue', 'Tall'], 'Ryan': ['21', 'U.S.', 'Green', 'Short']}

In python 3 you can use a more elegant way with unpacking operation :

>>> {i:j for i,*j in list1}
{'James': ['24', 'Canada', 'Blue', 'Tall'], 'Ryan': ['21', 'U.S.', 'Green', 'Short']}
like image 196
Mazdak Avatar answered Dec 04 '22 07:12

Mazdak