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?
Go straight to a dict
with the tuples like:
patternMap = dict(x.split('=') for x in foo)
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)
{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}
{'super capital': 'BLUE', 'super foo': 'RED'}
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With