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

Question

Asked By – Rick

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])

Now we will see solution for issue: How can I get dictionary key as variable directly in Python (not by searching from value)?


Answer

You should iterate over keys with:

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

This question is answered By – systempuntoout

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0