Вопрос

I am trying to create a simple dictionary of each letter with a number afterward (from 1-26), like this: {'a': 1, 'b': 2, 'c': 3, ...}. I wanted to try using a dictionary comprehension to do this, so I did:

from string import lowercase
d = {s:i for s in lowercase for i in range(1, 27)}

However, this results in: {'a': 26, 'b': 26, 'c': 26, ...}. I think this happens because it's iterating over every value in lowercase, assigning it to 1, then 2, then 3 (for every value) ending at 26. There are only 26 keys because since it's a dictionary, it won't have two keys of the same letter (so it overwrites all of them to 26 at the end). I am not sure how to fix this, so if I could get guidance on how to actually do this, that would be great.

I got it to work using dict() and zip(): dict(zip(lowercase, range(1, 27))). However, I want to know how to do this using a dictionary comprehension. Thanks!

Это было полезно?

Решение

With enumerate:

{s: i for i, s in enumerate(lowercase, 1)}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top