Search code examples
pythondictionarydictionary-comprehension

Why this dictionary values are all the same?


I am trying to write this dictionary comprehension and I don't know why all the dictionary values are the same.

The code is:

from string import ascii_uppercase

dictionary = {key: value for key in range(0, len(ascii_uppercase)) for value in ascii_uppercase}

The result is:

{0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z', 4: 'Z', 5: 'Z', 6: 'Z', 7: 'Z', 8: 'Z', 9: 'Z', 10: 'Z', 11: 'Z', 12: 'Z', 13: 'Z', 14: 'Z', 15: 'Z', 16: 'Z', 17: 'Z', 18: 'Z', 19: 'Z', 20: 'Z', 21: 'Z', 22: 'Z', 23: 'Z', 24: 'Z', 25: 'Z'}

Why it is only giving me the last character of the string as all the values? How can I fix it?


Solution

  • If you convert the dict comprehension into regular loops, you have this:

    dictionary = {}
    for key in range(0, len(ascii_uppercase)): # for every number in range 0-26
        for value in ascii_uppercase:          # for every letter in range a-z
            dictionary[key] = value            # d[num] = letter
    

    The last letter for every number is 'z' so your dictionary is updated with it at the end of inner loop for each number.

    You can try:

    di = {}
    for i, letter in enumerate(ascii_uppercase):
        di[i] = letter
    

    or

    di = {i: letter for i, letter in enumerate(ascii_uppercase)}
    

    or

    di = dict(enumerate(ascii_uppercase))