我们如何使用get()获取密钥而不是值?
namelist = {0:"Ace", 1: "King", 2:"Queen", 3:"Jack", 4:"10",5:"9"}
我想为女王获得2分。
答案 0 :(得分:1)
生成如下的逆字典:
inverse_namelist = {v: k for k, v in namelist.items()}
然后你可以简单地将它用作字典,就像你获得密钥一样。
答案 1 :(得分:1)
你可以试试这个
>>> namelist = {0:"Ace", 1: "King", 2:"Queen", 3:"Jack", 4:"10",5:"9"}
>>> for i in namelist:
... if namelist.get(i) == "Queen":
... print(i)
...
2
注意 - 这并不意味着这样做,当你知道密钥而不是反之时,字典用于访问值。在您的情况下,最好拥有list
数据结构,与namelist = ["Ace", "King", "Queen", "Jack", "10","9"}
中一样,您可以Queen
namelist.index("Queen")
答案 2 :(得分:0)
def getFromValue(dictionary, choice):
for key, value in dictionary.items():
if value == choice:
return key
nameDict = {0:"Ace", 1: "King", 2:"Queen", 3:"Jack", 4:"10",5:"9"}
choice="Queen"
print getFromValue(nameDict, choice)