0

For example, if I want to pair every letter in the english alphabet with a number for its position as a dictionary, how would I do that without having to create a new dictionary every time like this:

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

1

Off the top of my head, here are a few different ways of doing it (by no means exhaustive):

from string import ascii_lowercase as alphabet
from itertools import count

mapping = dict(zip(alphabet, count(start=1)))
print(mapping)

OR:

from string import ascii_lowercase as alphabet

mapping = {key: value for value, key in enumerate(alphabet, start=1)}
print(mapping)

OR:

from string import ascii_lowercase as alphabet

mapping = {char: ord(char)-ord('a')+1 for char in alphabet}
print(mapping)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15