如何在python中解析`key1:val1,val2,val3,key2:val1,val2`?

时间:2015-03-17 21:26:22

标签: python-2.7

给定一个str作为key1:val1,val2,val3,key2:val11,val22,分割字符串的最有效方法是:

key1: ['val1', 'val2', 'val3']
key2: ['val11', 'val22']

谢谢

1 个答案:

答案 0 :(得分:1)

In [150]: answer = {}

In [151]: s = "key1:val1,val2,val3,key2:val11,val22"

In [152]: for pair in s.split(','):
    k, _, v = pair.rpartition(":")
    if k: key = k
    if key not in answer: answer[key] = []
    answer[key].append(v)
   .....:     

In [153]: for k,vals in answer.items():
    print(k, ":", vals)
   .....:     
key2 : ['val11', 'val22']
key1 : ['val1', 'val2', 'val3']