Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to construct a dictionary comprehension from a list of unparsed strings without double split? [duplicate]

Consider the following dictionary comprehension:

foo = ['super capital=BLUE', 'super foo=RED']
patternMap = {x.split("=")[0]:x.split("=")[1] for x in foo}

It is fairly concise, but I don't like the fact that I need to call x.split('=') twice. I tried the following but it just results a syntax error.

patternMap = {y[0] : y[1] for y in x.split('=') for x in foo}

Is there a "proper" way to achieve the result in the first two lines without having to call x.split() twice or being more verbose?

like image 303
merlin2011 Avatar asked Feb 27 '18 04:02

merlin2011


2 Answers

Go straight to a dict with the tuples like:

Code:

patternMap = dict(x.split('=') for x in foo)

Test Code:

foo = ['super capital=BLUE', 'super foo=RED']
patternMap = {x.split("=")[0]: x.split("=")[1] for x in foo}
print(patternMap)

patternMap = dict(x.split('=') for x in foo)
print(patternMap)

# or if you really need a longer way
patternMap = {y[0]: y[1] for y in (x.split('=') for x in foo)}
print(patternMap)

Results:

{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}
like image 92
Stephen Rauch Avatar answered Nov 15 '22 11:11

Stephen Rauch


I don't know if it's more verbose or not, but here's an alternative without calling split twice:

patternMap = {x1:x2 for x1, x2 in map(lambda f: f.split('='), foo)}
like image 43
damores Avatar answered Nov 15 '22 11:11

damores