How to print a dictionary's key?

前端 未结 20 818
眼角桃花
眼角桃花 2020-11-27 09:22

I would like to print a specific Python dictionary key:

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

Now I can check if mydic.has_

20条回答
  •  迷失自我
    2020-11-27 09:35

    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.

提交回复
热议问题