Benjamin Benjamin - 1 year ago 104
Python Question

Python: how to print a dictionary's key?

I found a my question in SO already, but it was not answered directly. I would like to print a specific Python dictionary key:

mydic = {}
mydic['key_name'] = 'value_name'

Now I can check if
, but what I would like to do is print the name of the key
. Of course I could use
, 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
method to print a key name?

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
are two different things and i thought it would incorrect to print the
out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)

Answer Source

A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

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

Python 3 version:

for key, value in mydic.items() :
    print (key, value)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download