Create a list of lists from a string

I want to convert a string such as' a = b, a = c, a = d, b = e 'to dict 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 overly complicated.

Any better solutions?

+4
source share
4 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 are 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 
+13
source
 >>> 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']} 
+6
source

What about...

 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] 
0
source

Using a regular expression allows only two sections to work on two sections:

 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 
0
source

Source: https://habr.com/ru/post/1341817/


All Articles