可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 would be a fast way of generating that dict, rather than me having to type it in?
Thanks for your help.
EDIT
Thanks everyone for your solutions :)
nosklo's
solution is probably the shortest
Also, thanks for reminding me about the Python string module.
回答1:
I find this solution more elegant:
import string
d = dict.fromkeys(string.ascii_lowercase, 0)
回答2:
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})
回答3:
If you plan to use it for counting, I suggest the following:
import collections
d = collections.defaultdict(int)
回答4:
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}
回答5:
Yet another 1-liner Python hack:
letter_count = dict([(chr(i),0) for i in range(97,123)])
回答6:
There's this too:
import string
letter_count = dict((letter, 0) for letter in string.ascii_lowercase)
回答7:
import string
letters = string.ascii_lowercase
d = dict(zip(letters, [0]*len(letters))
回答8:
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)
回答9:
A dictionary whith the letters of the alphabet as keys and the value is the same as the key:
d = {'z': 'z', 'p': 'p', 'a': 'a', 'c': 'c', 'o': 'o', 'g': 'g', 'd': 'd', 'k': 'k', 'f': 'f', 'v': 'v', 'm': 'm', 'x': 'x', 'q': 'q', 'y': 'y', 'r': 'r', 'h': 'h', 'n': 'n', 'l': 'l', 'j': 'j', 'u': 'u', 'i': 'i', 'b': 'b', 's': 's', 'w': 'w', 'e': 'e', 't': 't'}
d = dict.fromkeys(string.ascii_lowercase, 0)
count=97
for i in range(26):
d[chr(count)]=chr(count)
count=count+1