Python what is the best way to get the key from dict by value (in terms of runtime speed)
Question:
So let’s suppose I have the following dictionary:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
The question is what is the best way to get the key of a given value. For instance, I want to get a key in dictionary which one’s value contains A2
:
def get_key_depending_on_value(value):
for key in data.keys():
if value in data[key]:
return key
return 'There is no such string in data's values'
result = get_key_depending_on_value('A2')
print(result) # prints A
I could have written such a function, but is it the best practice or python has something built in?
Answers:
I suggest you generate a new dictionary:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
d = {}
for key, values in data.items():
d.update({value: key for value in values})
Now you can just do d[value]
to get the key.
So let’s suppose I have the following dictionary:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
The question is what is the best way to get the key of a given value. For instance, I want to get a key in dictionary which one’s value contains A2
:
def get_key_depending_on_value(value):
for key in data.keys():
if value in data[key]:
return key
return 'There is no such string in data's values'
result = get_key_depending_on_value('A2')
print(result) # prints A
I could have written such a function, but is it the best practice or python has something built in?
I suggest you generate a new dictionary:
data = {
'A': ['A1', 'A2', 'A3'],
'B': ['B1', 'B2', 'B3'],
}
d = {}
for key, values in data.items():
d.update({value: key for value in values})
Now you can just do d[value]
to get the key.