1

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.

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
cidetto
  • 43
  • 2
  • 9

2 Answers2

0

Assuming ascii_lowercase comes from the built-in string module, you'd do this:

{item: i for i, item in enumerate(ascii_lowercase + ' ')}

But should the index sequence start at 0 or 1? You can control that via the start argument of enumerate (the default value is 0).

If the sequence must be 0-based and you need to skip index 26, you'll need to do something like

{item: i for i, item in (*enumerate(ascii_lowercase), (27, ' '))}
vaultah
  • 44,105
  • 12
  • 114
  • 143
0

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.

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73