Creating Dict Where Keys Are Alphabet Letters And Values Are 1-26 Using Dict Comprehension
Solution 1:
You can avoid the dict-comprehension altogether:
>>> importstring
>>> dict(zip(string.ascii_lowercase, range(1,27)))
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
With an OrderedDict:
>>> import string
>>> from collections import OrderedDict
>>> OrderedDict(zip(string.ascii_lowercase, range(1,27)))
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7), ('h', 8), ('i', 9), ('j', 10), ('k', 11), ('l', 12), ('m', 13), ('n', 14), ('o', 15), ('p', 16), ('q', 17), ('r', 18), ('s', 19), ('t', 20), ('u', 21), ('v', 22), ('w', 23), ('x', 24), ('y', 25), ('z', 26)])
I'd use a dict-comprehension only if you have to do some more computation to get the key/value or if it enhances readability (extreme example: {noun : age for noun, age in something()} gives you an idea of what we are talking about while dict(something()) does not).
Solution 2:
My take on it:
from string import ascii_uppercase
from collections import OrderedDict
od = OrderedDict((ch, idx) for idx, ch inenumerate(ascii_uppercase, 1))
Or:
from itertools import count, izipod= OrderedDict(izip(ascii_uppercase, count(1)))
Solution 3:
Use enumerate() to count the letters:
>>> OrderedDict((k,v+1) for v,k in enumerate(string.ascii_uppercase))
OrderedDict([('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6), ('G', 7), ('H', 8), ('I', 9), ('J', 10), ('K', 11), ('L', 12), ('M', 13), ('N', 14), ('O', 15), ('P', 16), ('Q', 17), ('R', 18), ('S', 19), ('T', 20), ('U', 21), ('V', 22), ('W', 23), ('X', 24), ('Y', 25), ('Z', 26)])
To answer the question at the end of the post, a dict comprehension is not an appropriate way to initialise an OrderedDict. Dict comprehensions only create ordinary dictionaries and if you use that to initialise your OrderedDict it is already too late, you have lost any ordering.
Solution 4:
theDict ={chr(y):y-64for y inrange(65,91)
print theDict
Output:
{'A':1,'B':2,......'X':24,'Y':25,'Z':26}
Solution 5:
The easiest way is to use zip and tuple unpacking
importstring
{ k: v for k, v in zip(string.ascii_uppercase, xrange(1, len(string.ascii_uppercase)+1))}
Edited to take comments into account. It's a one liner, no dict comp. Just relies on OrderedDict taking an iterable and the power of zip.
OrderedDict(zip(string.ascii_uppercase, xrange(1, len(string.ascii_uppercase)+1)))
Post a Comment for "Creating Dict Where Keys Are Alphabet Letters And Values Are 1-26 Using Dict Comprehension"