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

前端 未结 11 1718
终归单人心
终归单人心 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:29

    Here's a compact version, using a list comprehension:

    >>> import string
    >>> letter_count = dict( (key, 0) for key in string.ascii_lowercase )
    >>> letter_count
    {'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0,
     'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 
    't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
    
    0 讨论(0)
  • 2020-12-23 13:33

    You can use dictionary and range directly, so you can create your own function and easily customize it.

    def gen_alphabet(start, value):
        return {chr(ord('a') + i) : 0 for i in range(value)}
    
    print(gen_alphabet('a', 26))
    

    OUTPUT:

    >>> {'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
    
    0 讨论(0)
  • 2020-12-23 13:35
    import string
    letters = string.ascii_lowercase
    d = dict(zip(letters, [0]*len(letters))
    
    0 讨论(0)
  • 2020-12-23 13:37

    My variant :

    Note : range A-Z in unicode => 65-90 (decimal)

    d = dict.fromkeys([chr(j) for j in range(65, 90)], 0)
    print(d)
    

    OUTPUT :

    >>> {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0}
    
    0 讨论(0)
  • 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})
    
    0 讨论(0)
  • 2020-12-23 13:46

    I find this solution more elegant:

    import string
    d = dict.fromkeys(string.ascii_lowercase, 0)
    
    0 讨论(0)
提交回复
热议问题