Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
Ris Avatar asked Feb 15 '13 20:02

Ris


People also ask

How lists can be used as keys in dictionaries?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Can a dict be a key?

Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.


2 Answers

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))
like image 107
Ashwini Chaudhary Avatar answered Sep 20 '22 06:09

Ashwini Chaudhary


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)))
like image 33
Andrew Clark Avatar answered Sep 20 '22 06:09

Andrew Clark