Ris
Ris

Reputation: 1912

How to create a dict with letters as keys in a concise way?

I created an dictionary of the 26 alphabet letters like this:

aDict={
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    etc...
}

I'm trying make my code better and my question is, is there any shorter way to do this without typing all these numbers out?

Upvotes: 8

Views: 10634

Answers (5)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251116

You can use string.ascii_lowercase and dict comprehension here.

In [4]: from string import ascii_lowercase as al

For Python 2.7+:

In [5]: dic = {x:i for i, x in enumerate(al, 1)}

For Python 2.6 or earlier:

In [7]: dic = dict((y, x) for x, y in enumerate(al, 1))

Upvotes: 17

schesis
schesis

Reputation: 59178

Python 2.7 and above:

import string

letters = {k: v for v, k in enumerate(string.ascii_lowercase, 1)}

Python 2.6 and below:

import string

letters = dict((k, v) for v, k in enumerate(string.ascii_lowercase, 1))

Upvotes: 1

wrgrs
wrgrs

Reputation: 2569

You can find the ascii value of a character using ord() function, and the reverse is chr():

>>> ord('a')
97

You can then create a dictionary from the ascii values as follows:

for i in range(97, 97+26):
    x[chr(i)] = i - 96 

Upvotes: 1

Óscar López
Óscar López

Reputation: 236124

Try this, it works in Python 2.6 and older:

from string import ascii_lowercase
d = {}
for i, c in enumerate(ascii_lowercase, 1):
    d[c] = i

If you're using Python 2.7 or newer, you can use a dictionary comprehension:

d = {c : i for i, c in enumerate(ascii_lowercase, 1)}

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208615

aDict = dict(zip('abcdefghijklmnopqrstuvwxyz', range(1, 27)))

Or instead of hard coding the alphabet:

import string
aDict = dict(zip(string.ascii_lowercase, range(1, 27)))

Upvotes: 6

Related Questions