[Tutor] Finding the key for a value in a dictionary.

Wesley Brooks wesbrooks at gmail.com
Thu Jan 11 12:09:07 CET 2007

Cheers for the reply.

I'm creating a custom dictionary that I can use to store list of
unique objects used in a GUI. Items are added then a unique string is
returned. I have used this approach so if an item is deleted from the
storage dictionary I can still find it using the key, where as if I
had used a list I would have to update all references to an object if
an object before it in the list was deleted as it's index would


On 11/01/07, Kent Johnson <kent37 at tds.net> wrote:
> Wesley Brooks wrote:
> > Dear Users,
> >
> > I'm trying to find the key of a unique value within a dictionary. Is
> > the code bellow a safe way of doing so, or is there a better way of
> > doing it?
> >
> > a = {'de':'df', 'gf':'hg'}
> > key = a.keys()[a.values().index('hg')]
> This is safe, as long as the dict is not being modified (by another
> thread, presumably) while this is going on - the docs for dict
> explicitly guarantee that the order of items in a.keys() and a.values()
> will correspond as long as a doesn't change.
> Whether it is a good solution or not, I don't know. It sounds like your
> dictionary is backwards, maybe, if you are looking up by value.
> Kent

More information about the Tutor mailing list