Mapping characters to their position in the alphabet


Creates a dictionary named char_alphabet_position using a dictionary comprehension in Python. This dictionary maps lowercase letters of the English alphabet to their respective positions in the alphabet, starting from 1. Here's a step-by-step explanation of the code:

  • import string: This line imports the string module, which provides a string constant string.ascii_lowercase containing all lowercase letters of the English alphabet.
  • char_alphabet_position = {char: string.ascii_lowercase.index(char) + 1 for char in string.ascii_lowercase}: This line creates the char_alphabet_position dictionary using a dictionary comprehension. Here's how it works:
    • {char: string.ascii_lowercase.index(char) + 1 for char in string.ascii_lowercase} is the dictionary comprehension. It performs the following steps:
    • string.ascii_lowercase is the string containing all lowercase letters of the English alphabet: "abcdefghijklmnopqrstuvwxyz."
    • for char in string.ascii_lowercase iterates over each lowercase letter in the alphabet.
    • string.ascii_lowercase.index(char) finds the index (position) of the character char within the string string.ascii_lowercase. This index is a zero-based index.
    • + 1 is added to the index to shift it from a zero-based index to a one-based position, as positions in the alphabet start from 1.
    • It creates a key-value pair in the dictionary, where the key (char) is the lowercase letter, and the value (string.ascii_lowercase.index(char) + 1) is its position in the alphabet.
  • print(char_alphabet_position): This line prints the char_alphabet_position dictionary to the console.

Source Code

import string
 
char_alphabet_position = {char: string.ascii_lowercase.index(char) + 1 for char in string.ascii_lowercase}
print(char_alphabet_position)

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}

Example Programs