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.
A dictionary is 6.6 times faster than a list when we lookup in 100 items.
The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
I find this solution more elegant:
import string d = dict.fromkeys(string.ascii_lowercase, 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With