如何打印字典的鍵? - How to print a dictionary's key?

問題:

I would like to print a specific Python dictionary key:我想打印一個特定的 Python 字典鍵:

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' .現在我可以檢查mydic.has_key('key_name') ,但我想做的是打印密鑰'key_name'的名稱。 Of course I could use mydic.items() , but I don't want all the keys listed, merely one specific key.當然,我可以使用mydic.items() ,但我不想列出所有的鍵,只需要一個特定的鍵。 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?是否有任何name_the_key()方法來打印密鑰名稱?


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.我只是感到困惑,因爲我意識到 key_name 和mydic['key_name']是兩個不同的東西,我認爲從字典上下文中打印key_name是不正確的。 But indeed i can simply use the 'key_name' to refer to the key!但確實我可以簡單地使用“key_name”來引用密鑰! :) :)


解決方案:

參考一: https://en.stackoom.com/question/Om9R
參考二: https://stackoom.com/question/Om9R
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章