Create dictionary with alphabet characters mapping to numbers

Viewed 3850

I want to write a code in Python, which assigns a number to every alphabetical character, like so: a=0, b=1, c=2, ..., y=24, z=25. I personally don't prefer setting up conditions for every single alphabet, and don't want my code look over engineered. I'd like to know the ways I can do this the shortest (meaning the shortest lines of code), fastest and easiest. (What's on my mind is to create a dictionary for this purpose, but I wonder if there's a neater and better way). Any suggestions and tips are in advance appreciated.

4 Answers

You definitely want a dictionary for this, not to declare each as a variable. A simple way is to use a dictionary comprehension with string.ascii_lowercase as:

from string import ascii_lowercase

{v:k for k,v in enumerate(ascii_lowercase)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5...

Here's my two cents, for loop will do the work:

d = {} #empty dictionary

alpha = 'abcdefghijklmnopqrstuvwxyz'

for i in range(26):
    d[alpha[i]] = i #assigns the key value as alphabets and corresponding index value from alpha string as the value for the key

print(d) #instant verification that the dictionary has been created properly

There are already numbers associated with characters. You can use these code points with ord().
A short (in terms of lines) solution would be:

num_of = lambda s: ord(s) - 97

A normal function would be easier to read:

def num_of(s):
    return ord(s) - 97

Usage:

num_of("a") # 0
num_of("z") # 25

If it must be a dictionary you can create it without imports like that:

{chr(n):n-97 for n in range(ord("a"), ord("z")+1)}

One-liner with map and enumerate:

# given
foo = 'abcxyz'
dict(enumerate(foo))

# returns: {0: 'a', 1: 'b', 2: 'c', 3: 'x', 4: 'y', 5: 'z'}

If you needed it with the characters as the dictionary keys, what comes into my mind is either a dict comprehension...

{letter:num for (num,letter) in enumerate(foo) }

# returns {'a': 0, 'b': 1, 'c': 2, 'z': 3, 'y': 4, 'x': 5}

... or a lambda...

dict( map(lambda x: (x[1],x[0]), enumerate(foo)) )

# returns {'a': 0, 'b': 1, 'c': 2, 'z': 3, 'y': 4, 'x': 5}

I feel dict comprehension is much more readable than map+lambda+enumerate.

Related