使用get()从字典中提取密钥

时间:2015-03-27 09:26:11

标签: python python-3.x dictionary

我们如何使用get()获取密钥而不是值?

namelist = {0:"Ace", 1: "King", 2:"Queen", 3:"Jack", 4:"10",5:"9"}

我想为女王获得2分。

3 个答案:

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