简体   繁体   中英

How to find a tuple as value on a dictionary and get its key

I need to get the key by the given tuple destino which I have to find in the list transformed into a dictionary:

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

I corrected a few smaller mistakes in your for loop. Is this what you need?

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)

Firstly, better to iterate together over the (key, value) pairs. Secondly, you are looking for destino in val instead of the other way. Thirdly, if you find destino in val , you know that destinos_dict[key] will contain it.

Because of the fact that destino_dict contains more than one tuple in its values, you have to look if your tuple is in the dictionary value, not only look if it's the same value ( == ).

for k, v in destinos_dict.items():
    if destino in v:
        print k
    else:
        print "Destino not found"

Also you can use dict.items and then you only have to return k instead of looking up destinos_dict again.

What happens here is that val is a list and you need to iterate over it to be able to compare the values. It seems to me that in python 2 instead of .items() is .iteritems() .

for key,val in destinos_dict.items():
    print(val[0])
    if val[0]==destino:
        print(key)
    else:
        print("Destino not found")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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