Is it possible to build a dictionary understanding from a list of inseparable strings without double splitting?

Consider the following dictionary understanding:

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

It's pretty eloquent, but I don't like the fact that I need to call twice x.split('='). I tried the following, but that just leads to a syntax error.

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

Is there a “right” way to achieve the result in the first two lines without calling x.split()twice or more verbose?

+4
source share
2 answers

Go straight to dictusing tuples such as:

The code:

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

Security 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'}
+6
source

, , split :

patternMap = {x1:x2 for x1, x2 in map(lambda f: f.split('='), foo)}
0

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


All Articles