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
Loop through the entries of your list and add them to the dictionary:
for entry in list:
dict[entry[0]]=entry[1:]
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']}
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