How to create a letter in the form of keys in short form?

I created a dictionary of 26 letters of the alphabet as follows:

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

I am trying to make my code better and my question is, is there a shorter way to do this without typing all these numbers?

+8
python dictionary
source share
6 answers

You can use string.ascii_lowercase and understand it 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)) 
+17
source share
 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))) 
+6
source share

Try this, it works in Python 2.6 and later:

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

If you are using Python 2.7 or later, you can use dictionary understanding:

 d = {c : i for i, c in enumerate(ascii_lowercase, 1)} 
+2
source share

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

 >>> ord('a') 97 

Then you can create a dictionary from ascii values โ€‹โ€‹as follows:

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

Python 2.7 and later:

 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)) 
+1
source share
 dict([(chr(i),i-96) for i in range(97,123)]) 

But I like the @Ashwini Chaudhary method: it seems a lot cleaner.

0
source share

All Articles