[Tutor] How to get a key from dictionary?

Isaac Hall hall@phyast.nhn.ou.edu
Mon, 25 Mar 2002 17:23:14 -0600


I had a similar question not long ago.  My case was a little different (maybe)
in that I was gauranteed a one to one mapping between key and value.  I found
that provided the dictionary was not too long, the easiest solution was to
create 2 entries for every one which you have.  for instance, in the example
below you would have:

dict = {'aa':1, 'bb':2, 1:'aa', 2:'bb'}
then 
dict[1]
will give the desired 'aa'

however, this obviously does not work if there is not a one to one mapping (ie
if a value has more than one key).  If that is the case, then the best way I
have thought of so far is to place a list as the value for each new key.

for instance:
if your original dictionary is:
dict = {'aa':1, 'bb':2, 'cc':1}
then we want to make our new dictionary be:
dict = {'aa':1, 'bb':2, 'cc':1, 1:['aa','cc'], 2:['bb']}

if the dictionary is too large to do this by hand, we can automate it

def addtodict(dict):                          # Import a normal dictionary
    for key in dict.has_key():             # loop over all keys
        if dict[dict[key]]:                      #see if we already have an
                                                    #entry for each value   
            dict[dict[key]].append(key)    #if so, append to it
        else:
            dict[dict[key]] = [key]             #if not create it 

I haven't tested this, but something of this nature should work.  this will
take a little bit of time out of the program (depending on how large the
dictionary is) but for modestly sized dictionaries, should not be a problem
also note, that we can make all values in the dictionary to be lists and make
this much more complicated, but hopefully this will be enough to get you
started.

Ike 

On Mon, 25 Mar 2002, 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')
> 
> Thank you for help
> Ladislav
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor