在使用枚举函数创建字典时压缩字典条目

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

有没有办法在一行中写下以下内容?

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

我试过

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

但运气不好。

假设 ascii_lowercase 来自内置字符串模块,您可以这样做:

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

但是索引序列应该从 0 还是 1 开始?您可以通过 enumeratestart 参数来控制它(默认值为 0)。

如果序列必须从 0 开始并且你需要跳过索引 26,你需要做类似

的事情
{item: i for i, item in (*enumerate(ascii_lowercase), (27, ' '))}

Python >=3.5 使用字典扩展的解决方案

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

话虽如此,您的解决方案可读性很强,我更喜欢它。但这是您最接近尝试的结果。