How can I get dictionary key as variable directly in Python (not by searching from value)?

Rick picture Rick · Aug 23, 2010 · Viewed 709.5k times · Source

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries... what I am trying to do is this:

mydictionary={'keyname':'somevalue'}
for current in mydictionary:

   result = mydictionary.(some_function_to_get_key_name)[current]
   print result
   "keyname"

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

I have seen the method below but this seems to just return the key's value

get(key[, default])

Answer

systempuntoout picture systempuntoout · Aug 23, 2010

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])