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

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

    There's this too:

    import string
    letter_count = dict((letter, 0) for letter in string.ascii_lowercase)
    
    0 讨论(0)
  • 2020-12-23 13:48

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

    import collections
    d = collections.defaultdict(int)
    
    0 讨论(0)
  • 2020-12-23 13:48
    a_to_z = [(chr(i+64), chr(i+64)) for i in range(1, 27)]
    

    Output

    [('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ('E', 'E'), ('F', 'F'), ('G', 'G'), ('H', 'H'), ('I', 'I'), ('J', 'J'), ('K', 'K'), ('L', 'L'), ('M', 'M'), ('N', 'N'), ('O', 'O'), ('P', 'P'), ('Q', 'Q'), ('R', 'R'), ('S', 'S'), ('T', 'T'), ('U', 'U'), ('V', 'V'), ('W', 'W'), ('X', 'X'), ('Y', 'Y'), ('Z', 'Z')]
    
    0 讨论(0)
  • 2020-12-23 13:50

    Yet another 1-liner Python hack:

    letter_count = dict([(chr(i),0) for i in range(97,123)])
    
    0 讨论(0)
  • 2020-12-23 13:50

    very easy with dictionary comprehensions : {chr(i+96):i for i in range(1,27)} generates :

    {'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}

    You can generate the same for Capital A-Z with chr(i+64)

    0 讨论(0)
提交回复
热议问题