在复杂字典中按值获取密钥

时间:2017-09-19 04:19:38

标签: python loops dictionary

我想知道如何根据它是否包含某个值来返回字典的键。如下图所示:

dic = {1: [(3,3)], 2: [(1, 2), (2, 3), (1, 3), (4, 3)]}

def get_key(pos):

    for key, value in dic.items():
        if value == pos:
           return key

如您所见,该函数接受一个参数并检查它是否在字典中。如果是这样,它应该返回相应的密钥。

我一直在搜索其他类似于我的StackOverflow问题,但是,这些解决方案似乎不起作用。

4 个答案:

答案 0 :(得分:1)

以下代码可行:

def get_key(pos):
    dic = {1: [(3,3)], 2: [(1, 2), (2, 3), (1, 3), (4, 3)]}
    for (key, value) in dic.items():
        if pos in value:
            return key
  

pos =(1,2)

     

get_key(POS)

     

输出:2

值以列表形式返回,pos是单个元组。因此,您应该使用 IN 来检查pos是否在作为列表返回的元组集中。

答案 1 :(得分:0)

你可以传递第二个参数,它可以工作。

dic = {1: [(3,3)], 2: [(1, 2), (2, 3), (1, 3), (4, 3)]}

def get_key(pos, dic):

    for key, value in dic.items():
        if value == pos:
           return key

if __name__ == '__main__':
    print get_key([(3,3)], dic)

以下是输出

1
[Finished in 0.0s]

答案 2 :(得分:0)

你想在词典中搜索元组吗?

dic = {1: [(3,3)], 2: [(1, 2), (2, 3), (1, 3), (4, 3)]}
def get_key(pos):
    for key, value in dic.items():
        if pos in value:
           return key

get_key((2,3)) // output 2
get_key((3,3)) // output 1

答案 3 :(得分:0)

您可以使用lambda和单行过滤来解决这个问题。希望这会对您有所帮助

dic = {1: [(3,3)], 2: [(1, 2), (2, 3), (1, 3), (4, 3)]}

pos = (2,3)

get_key = filter(lambda x: pos in dic[x], dic)
print get_key[0]

您可以阅读lambda详细信息here