简体   繁体   English

为什么这段代码不用“”就可以访问字典?

[英]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.在 Python 中,通过键入digit_mapping.get("1") ,我可以访问此字典中的值 1。 I am wondering why it still can access the dictionary without "" around the character inside the get method in this code.我想知道为什么它仍然可以访问字典而没有在此代码中的 get 方法中的字符周围加上""

like output += digit_mapping.get("character", "!") + " "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.正如评论中提到的, character是一个变量。 It holds a value;它拥有一个价值; in your case, a string .在你的情况下,一个string "character" , on the other hand, is a string .另一方面, "character"是一个string In your example, "character" would return nothing, since the dictionary doesn't carry a key by that name.在您的示例中, "character"将不返回任何内容,因为字典不带有该名称的键。 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.在另一方面,该值使可变character包含( "1", "2", "3" and "4" ;对于内的每次迭代的值for -loop)是一个有效的key在字典中并且将产生字典中所需的value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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