Reputation: 13
a = {1897:("Diptojit", "Sealdah", 9000000001),
2224:("Debanjan", "Tarakeshwar", 9000000002),
1758: ("Avinesh", "Metropolitan", 9000000003),
2283: ("Biswajit", "Garia", 9000000004)}
n = input("Enter name to know index : ")
lk = list(a.keys())
lv = list(a.values())
#print(lv[0])
for i in range(0,4):
if n == "('Biswajit', 'Garia', 9000000004)":
print(lk[lv.index(n)])
break
I am trying to search a value and get its key as the output. This program shows no output while in case of a simple dictionary, when all keys have just one value, this code works perfectly. Please Help.
Upvotes: 1
Views: 251
Reputation: 237
You could iterate over every key value pair in the dictionary, and if the value matches the value you are finding, then you return the key. The method dict.items()
returns us an array of key value pairs, and we can iterate the array to find the value we want.
Eg:
def get_key_from_value(d, search_value):
for key, value in d.items(): # (("a", 1), ("b", 2), ("c", 3))
if value == search_value:
return key
return None
d = {"a": 1, "b": 2, "c": 3}
search_value = 2
key = get_key_from_value(d, search_value) # returns "b"
Edit:
dict.items()
returns an array of key value pairs, which we then destructure in the for loop as key
and value
. Then, for each iteration we compare it to the value we are searching for, and if it is the correct value, we return the key. If it isn't found, it returns None
.
To learn more about python destructuring: https://blog.teclado.com/destructuring-in-python/
Upvotes: 1
Reputation:
You can do the following:
import ast
...
...
for i,j in a.items():
if ast.literal_eval(n) == j:
print(i)
ast.literal_eval
safely evaluates the tuple since it is a string representation of the tuple. Then zip the lists containing keys and values and then check if that is equal to j
Upvotes: 1
Reputation: 1438
Use ast.literal_eval()
or eval()
(former is preferred [read why] though latter is part of the standard library) to convert input to tuple and match objects. Check out the following piece of code:
a = {1897:("Diptojit", "Sealdah", 9000000001),
2224:("Debanjan", "Tarakeshwar", 9000000002),
1758: ("Avinesh", "Metropolitan", 9000000003),
2283: ("Biswajit", "Garia", 9000000004)}
try: n = eval(input("Enter name to know index : ")) # converts input string to tuple for matching.
except: print("Invalid input format.")
for idx, details in a.items():
if n == details:
print(idx)
break
I have modified your code logic to work for generalized inputs.
Example input: Enter name to know index : ("Avinesh", "Metropolitan", 9000000003)
Example output: 1758
Upvotes: 0