Search code examples
pythondictionarydictionary-comprehension

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


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?


Solution

  • 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'}