Coding and Decoding in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 17 20:14:15 EDT 2011


On Thu, 17 Mar 2011 08:07:28 -0700, Wanderer wrote:

> I have a dll that to communicate with I need to send numeric codes. So I
> created a dictionary. It works in one direction in that I can address
> the key and get the value. But when the program returns the value I
> can't get the key.

If you only have a few keys:

def find_key(value, d):
    """Return the key in dictionary d that has the given value.
    If there are multiple keys with the same value, return an
    arbitrarily chosen one."""
    for k, v in d.items():
        if v == value: return k
    raise KeyError('no such value found')


If you have many keys/values, then simply create a reverse dictionary:

Rev_QCam_Info = {}
for key, value in QCam_Info.items():
    Rev_QCam_Info[value] = key

and then search that.




-- 
Steven




More information about the Python-list mailing list