简体   繁体   中英

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?

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))

Because the inner loop always end as the end of list, better is to Use enumerate() with dict() for this:

dictionary = dict(enumerate(ascii_uppercase))

The second for-loop gets fully executed before the first one so it messes up the result. You can try this approach with just one for-loop instead:

dictionary = {i: ascii_uppercase[i] for i in range(len(ascii_uppercase))}

Change your code to this

from string import ascii_uppercase

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

Output

{0: '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: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}

While there are other suitable answers, I believe this is what you think you are doing.

from string import ascii_uppercase


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM