Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionaries Values
#1
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]
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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}
Reply
#4
I have to pay more attention to zip(). Never using it. Dodgy
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  5 variants to invert dictionaries with non-unique values Drakax1 2 2,564 Aug-31-2020, 11:40 AM
Last Post: snippsat
  Accessing values in list of dictionaries pythonnewbie138 2 2,084 Aug-02-2020, 05:02 PM
Last Post: pythonnewbie138
  Passing Values of Dictionaries to Function & Unable to Access Them firebird 3 2,530 Aug-03-2019, 10:25 PM
Last Post: firebird
  Subtracting values between two dictionaries/ floating point numbers FloppyPoppy 5 5,829 Mar-04-2019, 01:00 PM
Last Post: snippsat
  [split] merge/display values from two dictionaries ramkumar_70 3 3,644 Oct-17-2017, 09:42 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020