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?
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.
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 {}.
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))
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With