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

前端 未结 11 1837
终归单人心
终归单人心 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}
    

提交回复
热议问题