简体   繁体   中英

Why this code can access the dictionary without “”?

In Python, by typing digit_mapping.get("1") , I can access value of one in this dictionary. I am wondering why it still can access the dictionary without "" around the character inside the get method in this code.

like output += digit_mapping.get("character", "!") + " "

phone = input("Phone: ")
digit_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for character in phone:
    output += digit_mapping.get(character, "!") + " "
print(output)

As mentioned in the comments, character is a variable. It holds a value; in your case, a string . "character" , on the other hand, is a string . In your example, "character" would return nothing, since the dictionary doesn't carry a key by that name. On the other hand, the value that the variable character contains ( "1", "2", "3" and "4" ; a value for each iteration within the for -loop) is a valid key in the dictionary and would yield the desired value from the dictionary.

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