将列表转换为Dict

Rav*_*lil 5 python dictionary python-2.7 python-3.x

当我有一个格式为的列表

list1 = [[James,24],[Ryan,21],[Tim,32]...etc] 
Run Code Online (Sandbox Code Playgroud)

我可以用

dic1 =dict(list1)
Run Code Online (Sandbox Code Playgroud)

但是现在让我说我有多个值,例如

list1 = [[James,24,Canada,Blue,Tall],[Ryan,21,U.S.,Green,Short
[Tim,32,Mexico,Yellow,Average]...etc]
Run Code Online (Sandbox Code Playgroud)

我不知道如何创建一个dict,以便它将第一个名称显示为键,将以下值显示为值.

提前致谢

Kas*_*mvd 16

你可以使用字典理解和切片:

>>> 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']}
Run Code Online (Sandbox Code Playgroud)

在python 3中,您可以使用更优雅的方式进行解包操作:

>>> {i:j for i,*j in list1}
{'James': ['24', 'Canada', 'Blue', 'Tall'], 'Ryan': ['21', 'U.S.', 'Green', 'Short']}
Run Code Online (Sandbox Code Playgroud)