Python Forum

Full Version: Dictionaries Values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import string
alphabet = string.ascii_letters
d = {}
for i in range(1,53):
    d = dict.fromkeys(alphabet,i)
print(d)
I want to create a dictionary of all letters in the alphabet and assign to each letter an integer.
I have no idea why is it assigning the same value for all of my keys
Help please

(Output)
Output:
{'a': '52', 'b': '52', 'c': '52', 'd': '52', 'e': '52', 'f': '52', 'g': '52', 'h': '52', 'i': '52', 'j': '52', 'k': '52', 'l': '52', 'm': '52', 'n': '52', 'o': '52', 'p': '52', 'q': '52', 'r': '52', 's': '52', 't': '52', 'u': '52', 'v': '52', 'w': '52', 'x': '52', 'y': '52', 'z': '52', 'A': '52', 'B': '52', 'C': '52', 'D': '52', 'E': '52', 'F': '52', 'G': '52', 'H': '52', 'I': '52', 'J': '52', 'K': '52', 'L': '52', 'M': '52', 'N': '52', 'O': '52', 'P': '52', 'Q': '52', 'R': '52', 'S': '52', 'T': '52', 'U': '52', 'V': '52', 'W': '52', 'X': '52', 'Y': '52', 'Z': '52'} [Finished in 0.17s]
You can use enumerate for the digits and loop over the letters:
for digit, char in enumerate (all_chars, 1): # enumerate starts from 1 instead 0 and goes to 'digit'. char holds one letter ( the for loop )
    my_dict[char] = digit
fromkeys(alphabet,i)
i is only evaluated with last value in loop.
wavic solution is good it will loop over all,then is no need to use range().

If using range(),it could be done like this:
>>> import string
>>> from pprint import pprint

>>> pprint(dict(zip(string.ascii_letters, range(1,15))))
{'a': 1,
 'b': 2,
 'c': 3,
 'd': 4,
 'e': 5,
 'f': 6,
 'g': 7,
 'h': 8,
 'i': 9,
 'j': 10,
 'k': 11,
 'l': 12,
 'm': 13,
 'n': 14}
I have to pay more attention to zip(). Never using it. Dodgy