For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
As noted in a comment, the whole thing can be written as a generator expression:
Python versions note: in Python 3+ you can use
dict.items()
instead ofdict.iteritems()
In Python 3:
Output:
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
you would change it to
or vice versa to set the key as the value and the value as the key so you can get the thing you want
I don't believe there is a way to do it. It's not how a dictionary is intended to be used... Instead, you'll have to do something similar to this.