[英]Change List to Dict Python
Imagine that you have:想象一下,你有:
value = ["Name:","Mike", "Hobby:", "bakset", "voly"]
What is the simplest way to produce the following dictionary?生成以下字典的最简单方法是什么?
output : {"Name:" : ["Mike"], "Hobby:" : ["bakset", "voly"]}
with python与 python
Value with ":" would be the key for dictionary带有“:”的值将是字典的键
Dict comprehension:字典理解:
>>> {v: (a := []) for v in value if v[-1] == ':' or a.append(v)}
{'Name:': ['Mike'], 'Hobby:': ['bakset', 'voly']}
Though I suspect you're not sharing the original data but already processed data, and that there's a better way to directly build from the original data.虽然我怀疑您没有共享原始数据,而是已经处理过的数据,并且有一种更好的方法可以直接从原始数据构建。 Possibly with an existing parser for the format.可能使用该格式的现有解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.