Get first element of sublist as dictionary key in python

余生长醉 提交于 2020-02-14 08:36:39

问题


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?


回答1:


Using dict comprehension :

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

output:

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



回答2:


Using dictionary comprehension (For Python 2.7 +) and slicing -

d = {e[0] : e[1:] for e in ll}

Demo -

>>> ll = [[1,2,3], [4,5,6], [7,8,9]]
>>> d = {e[0] : e[1:] for e in ll}
>>> d
{1: [2, 3], 4: [5, 6], 7: [8, 9]}



回答3:


you could do it this way:

ll = [[1,2,3], [4,5,6], [7,8,9]]
dct = dict( (item[0], item[1:]) for item in ll)
# or even:   dct = { item[0]: item[1:] for item in ll }
print(dct)
# {1: [2, 3], 4: [5, 6], 7: [8, 9]}



回答4:


Another variation on the theme:

d = {e.pop(0): e for e in ll}


来源:https://stackoverflow.com/questions/32604558/get-first-element-of-sublist-as-dictionary-key-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!