Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 794
Nope Avatar asked Jan 17 '09 16:01

Nope


People also ask

Which is faster dict or list in Python?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

Why is dict faster than list?

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.

Can you do a for loop for dictionary?

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.


1 Answers

I find this solution more elegant:

import string d = dict.fromkeys(string.ascii_lowercase, 0) 
like image 69
nosklo Avatar answered Sep 21 '22 15:09

nosklo