creating dict where keys are alphabet letters and values are 1-26 using dict comprehension

Padraic Cunningham picture Padraic Cunningham · Oct 23, 2013 · Viewed 25.4k times · Source
alphaValueDict = OrderedDict.fromkeys(string.ascii_uppercase,range(0)
i = 1
for k,v in alphaValueDict.iteritems():
    alphaValueDict[k] = [i]
    i += 1
return alphaValueDict

I need to create an ordered dict , where the keys are all the letters in the alphabet and the values are from 1 - 26. My question is, how can I use dict comprehension to do this in one line?

Answer

Bakuriu picture Bakuriu · Oct 23, 2013

You can avoid the dict-comprehension altogether:

>>> import string
>>> 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).