如何打印字典的关键字? [英] How to print a dictionary's key?

查看:186
本文介绍了如何打印字典的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我发现了一个我的问题,但没有直接回答。我想打印一个特定的Python字典键:

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

现在我可以检查 mydic.has_key('key_name' ),但我想做的是打印密钥的名称'key_name'。当然,我可以使用 mydic.items(),但我不希望列出所有的键所有,只是一个特定的键。例如,我希望这样(伪代码):

 打印密钥名称,mydic [ 'key_name']。name_the_key(),,其值为,mydic ['key_name'] 

是否有任何 name_the_key()方法来打印密钥名称?






编辑:
好​​的,谢谢你们的反应! :)我意识到我的问题没有很好的表达和微不足道的。我感到困惑,因为我意识到key_name和 mydic ['key_name'] 是两个不同的东西,我认为打印 key_name 出了字典上下文。但是我确实可以使用'key_name'来引用这个键! :)

解决方案

根据定义,字典具有任意数量的键。没有关键。您有 keys()方法,它为您提供了所有密钥的python 列表,并且您具有 iteritems()方法,它返回键值对,所以

  for key,mydic.iteritems()中的值:
打印键,值

Python 3版本:

 为密钥,mydic.items()中的值:
print(key,value)

所以你有一个关键字的句柄,但是如果耦合到一个值,它们只是真的意义上的意义。我希望我了解你的问题。


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 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! :)

解决方案

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.

这篇关于如何打印字典的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆