PYTHON:将属性值对的列表拆分为多键dict

时间:2017-06-14 01:41:36

标签: python list dictionary

我试图转换

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)

1 个答案:

答案 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']}