Is there a fast way to generate a dict of the alphabet in Python? Is there a fast way to generate a dict of the alphabet in Python? python python

Is there a fast way to generate a dict of the alphabet in Python?


I find this solution more elegant:

import stringd = dict.fromkeys(string.ascii_lowercase, 0)


import stringletter_count = dict(zip(string.ascii_lowercase, [0]*26))

or maybe:

import stringimport itertoolsletter_count = dict(zip(string.lowercase, itertools.repeat(0)))

or even:

import stringletter_count = dict.fromkeys(string.ascii_lowercase, 0)

The preferred solution might be a different one, depending on the actual values you want in the dict.


I'll take a guess here: do you want to count occurences of letters in a text (or something similar)? There is a better way to do this than starting with an initialized dictionary.

Use Counter from the collections module:

>>> import collections>>> the_text = 'the quick brown fox jumps over the lazy dog'>>> letter_counts = collections.Counter(the_text)>>> letter_countsCounter({' ': 8, 'o': 4, 'e': 3, ... 'n': 1, 'x': 1, 'k': 1, 'b': 1})


If you plan to use it for counting, I suggest the following:

import collectionsd = collections.defaultdict(int)