我试图转换
l = ['attr0=val1, val2', 'attr1=val3,val4']
到
d = {attr0: [val1, val2]; attr1: [val3, val4]}
有效/ pythonically。有人知道这样做的简明方法吗?
我尝试过类似的事情:
d = {}
for str in l:
k = str.split('=')[0]
v = str.split('=')[1]
d[k] = []
for item in v.split(','):
d[k].append(item)
答案 0 :(得分:1)
In[9]: test = ['attr0=val1, val2', 'attr1=val3,val4']
In[10]: result = {}
...: for attribute in test:
...: key, value = attribute.split('=')
...: result[key] = [a.strip() for a in value.split(',')]
...:
In[11]: result
Out[11]: {'attr0': ['val1', 'val2'], 'attr1': ['val3', 'val4']}