Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dict of lists from a string

I want to convert a string such as 'a=b,a=c,a=d,b=e' into a dict of lists {'a': ['b', 'c', 'd'], 'b': ['e']} in Python 2.6.

My current solution is this:

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(',')]))

which I'm sure is unnecessarily complicated.

Any better solutions?

like image 484
Chris Card Avatar asked Dec 01 '22 03:12

Chris Card


1 Answers

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

or, if you're using python > 2.4, you can use 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
like image 105
Shawn Chin Avatar answered Dec 04 '22 05:12

Shawn Chin