简体   繁体   English

Python:将列表转换成字典

[英]Python: convert list into dict

I have a list like below 我有一个像下面的清单

['position_Matrix position1', 'postal_code post10']

I was trying to make a dictionary based on this list and as expected below 我正在尝试根据此列表和下面的预期制作字典

{position_Matrix:position1, postal_code:post10}

Tried with below code and it doesn't work. 尝试使用下面的代码,它不起作用。 Can someone help on this? 有人可以帮忙吗?

dict(map(lambda x: x.split(" "), alias.split(",")))

Assuming alias is your list, the issue is that you're trying to split a list. 假设alias是您的列表,则问题在于您正在尝试拆分列表。 You almost had it right, just remove the split . 您几乎是正确的,只需删除split This will work: 这将起作用:

dict(map(lambda x: x.split(" "), alias))

You could also use a dict comprehension: 您还可以使用dict理解:

d = {x.split()[0]: x.split()[1] for x in some_list}
#equivalent and more efficient
d = dict(map(str.split, some_list)) # this would be my preferred solution
#another equivalent (ugly)
d = dict(zip(*[y.split() for y in x]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM