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


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:

for current in mydictionary:

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

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])
7/17/2014 6:33:50 PM

Accepted Answer

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])
8/7/2015 1:33:38 PM

If you want to print key and value, use the following:

for key, value in my_dict.iteritems():
    print key, value

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow