问题:
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