views:

79

answers:

3

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])
+2  A: 

You should iterate over keys with:

for key in mydictionary.keys():
   print "key: %s , value: %s" % (key, mydictionary[key])
systempuntoout
thanks this seems the most versatile solution
Rick
Why do you need `iterkeys()` here? In Python 2.x `for key in mydictionary` does the same thing and in 3.x there is no `iterkeys()` at all.
Constantin
@Constantin you are right.
systempuntoout
+5  A: 

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

for key, value in my_dict.iteritems():
    print key, value
Arrieta
+2  A: 

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

Based on the above requirement this is what I would suggest:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))
Manoj Govindan