Search code examples
pythondictionarylist-comprehensionenumeratedict-comprehension

Squeeze in an entry to a dictionary while creating the latter with enumerate function


Is there a way of writing the following on a single line?

x = {item: i for i, item in enumerate([letters for letters in ascii_lowercase])}
x[' '] = 27

I tried something like

x = {item: i for i, item in enumerate([letters for letters in ascii_lowercase]), ' ': 27}

but with no luck.


Solution

  • Python >=3.5 solution using dict expansion

    x = {**{item: i for i, item in enumerate(ascii_lowercase)}, **{' ' : 27}}
    

    With that said, your solution is very readable and I would prefer it over this. But this is the closest you can get to what you tried.