I would like to print a specific Python dictionary key:
mydic = {}
mydic['key_name'] = 'value_name'
Now I can check if mydic.has_key('key_name')
, but what I would like to do is print the name of the key 'key_name'
. Of course I could use mydic.items()
, but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):
print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']
Is there any name_the_key()
method to print a key name?
Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name']
are two different things and i thought it would incorrect to print the key_name
out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)
If you want to get the key of a single value, the following would help:
In pythonic way:
Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?
Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.
If you need to do this frequently, it would make sense to construct the reverse dictionary:
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the
keys()
method, which gives you a pythonlist
of all the keys, and you have theiteritems()
method, which returns key-value pairs, soPython 3 version:
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.
The name of the key 'key_name' is key_name, therefore
print 'key_name'
or whatever variable you have representing it.Note:In Python 3, dic.iteritems() was renamed as dic.items()