【发布时间】:2016-10-08 21:00:23
【问题描述】:
这是这个问题的延伸:How to split a string within a list to create key-value pairs in Python
与上述问题的不同之处在于我的列表中的项目并非都是键值对;有些项目需要赋值。
我有一个清单:
list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
我想创建一个字典:
dict = { 'abc':'ddd', 'ef':1, 'ghj':1, 'jkl':'yui', 'rty':1 }
我的想法是这样的:
a = {}
for item in list:
if '=' in item:
d = item.split('=')
a.append(d) #I don't I can do this.
else:
a[item] = 1 #feel like I'm missing something here.
【问题讨论】:
-
请附上您尝试过的代码及其存在的问题。
-
您需要一些解析器逻辑,它会检测包含“=”的列表元素并将其拆分为键和值。
标签: python string list dictionary