如何在查询字典中找到元组作为值并获取其键

时间:2018-08-16 17:05:04

标签: python dictionary tuples

我需要通过给定的元组destino来获取密钥,该元组必须在转换成字典的列表中找到:

destinos = [("AF10", [("Lima","Peru"), ("San Jose","Costa Rica")]),
    ("AF11", [("San Jose","Costa Rica"), ("Costa de Panama","Panama")])]


destino = ("Lima","Peru")
# could be any given tuple on the destinos list

destinos_dict = dict(destinos)
# destinos converted into a dictionary


for val in destinos_dict.values():
    if val == destino:
        print destinos_dict.key(destino)
    else:
        print "Destino not found"

# always print on the terminal the else statement, I want the if to be printed

3 个答案:

答案 0 :(得分:0)

我更正了您的for循环中的一些小错误。这是您需要的吗?

for  (key,val) in destinos_dict.items():
    if destino in val:
        print "'%s' with key '%s' contains '%s'" % (destinos_dict[key], key, destino)
    else:
        print "Destino '%s' not found in '%s' with key '%s'" % (destino, destinos_dict[key],key)

首先,最好在(key, value)对上一起进行迭代。其次,您正在destino中寻找val,而不是其他方式。第三,如果您在destino中找到val,则知道destinos_dict[key]将包含它。

答案 1 :(得分:0)

由于destino_dict的值中包含多个元组,因此您必须查看元组是否为in字典值,而不仅要查看其值是否相同({{ 1}})。

==

您还可以使用for k, v in destinos_dict.items(): if destino in v: print k else: print "Destino not found" ,然后只需返回dict.items,而不必再次查找destinos_dict。

答案 2 :(得分:0)

这里发生的是val是一个列表,您需要对其进行迭代才能比较这些值。在我看来,在python 2中,而不是<a class="theparent" href="/forum" target="_blank">FORUM</a> .items()

.iteritems()
相关问题