[Tutor] How to get a key from dictionary?
Lloyd Kvam
pythontutor@venix.com
Mon, 25 Mar 2002 18:39:31 -0500
Depending upon the values you are dealing with, and how often you need to
do the reverse lookup, you could build a reverse dictionary. Borrowing from
dman's example:
b_dict = {}
for item in a_dict.items()
[b_dict[item[1]] = item[0]
>>> b_dict
{2: 'bb', 1: 'aa'}
dman wrote:
> On Mon, Mar 25, 2002 at 11:16:28PM +0100, A wrote:
> | Hi,
> | Is there a possibility to get, from a dictionary, a key according to a
> | value ?
> | For example
> | I have a dictionary
> |
> | dict={'aa':1,'bb':2}
> |
> | and
> | dict['aa']
> | is 1
> |
> | But how can I for value 1 find out key? (That is here 'aa')
>
> That is not how dictionaries are intended to be used. It is possible,
> with a little work and a few CPU cycles, to work backwards like that.
> If you give more details regarding why you want to do this then
> perhaps we can suggest a more efficient solution. In the meantime,
>
> a_dict = { 'aa' : 1 , 'bb' : 2 }
> items = a_dict.items()
> VALUE = 1 # the value you want to find
> t = filter( lambda x : x[1] == VALUE , items )[0]
> key = t[0]
> print key
>
>
> What this does it get the list of (key,value) tuples from the
> dictionary, then iterate over it finding all the pairs that have the
> value you want to find. It then takes the first of those (bear in mind
> dicts can have duplicate values but not duplicate keys) and prints the
> key for that pair. This algorithm requires linear time. As the
> dictionary grows larger the time for this code to execute grows at the
> same rate.
>
> Also note that using 'dict' as a variable name is not recommended
> since it is a built-in name in python >= 2.2.
>
> HTH,
> -D
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582