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

前端 未结 11 1859
终归单人心
终归单人心 2020-12-23 13:05

I want to generate a dict with the letters of the alphabet as the keys, something like

letter_count = {\'a\': 0, \'b\': 0, \'c\': 0}

what

11条回答
  •  遥遥无期
    2020-12-23 13:44

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

    or maybe:

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

    or even:

    import string
    letter_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_counts
    Counter({' ': 8, 'o': 4, 'e': 3, ... 'n': 1, 'x': 1, 'k': 1, 'b': 1})
    

提交回复
热议问题