从字符串创建列表的字典

时间:2011-03-01 13:54:46

标签: python list dictionary merge

我想将一个字符串如'a = b,a = c,a = d,b = e'转换为列表的字典{'a':['b','c','d' ],'b':Python中的['e']}。

我目前的解决方案是:

def merge(d1, d2):
    for k, v in d2.items():
        if k in d1:
            if type(d1[k]) != type(list()):
                d1[k] = list(d1[k])
            d1[k].append(v)
        else:
            d1[k] = list(v)
    return d1

record = 'a=b,a=c,a=d,b=e'

print reduce(merge, map(dict,[[x.split('=')] for x in record.split(',')]))

我确信这是不必要的复杂。

有更好的解决方案吗?

4 个答案:

答案 0 :(得分:13)

d = {}
for i in 'a=b,a=c,a=d,b=e'.split(","):
    k,v = i.split("=")
    d.setdefault(k,[]).append(v)
print d

或者,如果您使用的是python> 2.4,您可以使用defaultdict

from collections import defaultdict

d = defaultdict(list)
for i in 'a=b,a=c,a=d,b=e'.split(","):
    k,v = i.split("=")
    d[k].append(v)
print d

答案 1 :(得分:6)

>>> result={}
>>> mystr='a=b,a=c,a=d,b=e'
>>> for k, v in [s.split('=') for s in mystr.split(',')]:
...     result[k] = result.get(k, []) + [v]
... 
>>> result
{'a': ['b', 'c', 'd'], 'b': ['e']}

答案 2 :(得分:0)

怎么样......

STR = "a=c,b=d,a=x,a=b"
d = {} # An empty dictionary to start with.

# We split the string at the commas first, and each substr at the '=' sign
pairs = (subs.split('=') for subs in STR.split(','))

# Now we add each pair to a dictionary of lists.
for key, value in pairs:
    d[key] = d.get(key, []) + [value]

答案 3 :(得分:0)

使用正则表达式允许仅在一个中执行两次拆分:

import re

ch ='a=b,a=c ,a=d,   b=e'

dic = {}
for k,v in re.findall('(\w+)=(\w+)\s*(?:,|\Z)',ch):
    dic.setdefault(k,[]).append(v)

print dic