Can you get the Key when you know the value, i.e., a "reverse" lookup?

I have set up the following dictionary

YearsToReferences: {"1841":"HO 107","1851":"HO 107","1861":"RG 09","1871":"RG 10","1881":"RG 11","1891":"RG 12","1901":"RG 13","1911":"RG 14","1921":"RG 15","1939":"RG 101"}

It works great if I know the year, e.g., 1901 gives me the value "RG 13". However sometimes I know the "RG 13" and want to know what the year was. I have done this by setting up another dictionary (ReferencesToYears) which also works fine. However it feels inelegant and duplicating effort.

So is there a way to find out the Key when you know the value ?

Dictionaries don't really work like that. Keys are unique, so you can easily find the value for a given key. But values don't have to be so you can't do the reverse -- the closest you can get is to go through every key and return all the ones that have the value you are looking for.

One way round this, when values are also unique across the data set, is to do what you've done -- set up a reciprocal dictionary. But you could consider a different data structure -- if your references are (relatively) unchanging, a simple text-based variable would do the job. One entry per line, year and reference separated by : -- then you could search by year and return the bit after the colon or search by reference and return the bit before.

Thanks Nige! And your suggestion helps with another question I didn't even ask! .. you get the clairvoyant prize! the list is completely unchanging and I can add a "third column" to get another piece of information, the date e.g., ... "1939 : RG 101 : 20 Sep 1939" and read the relevant parts by RegEx. Thanks much

Dave