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

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

问题描述

我想打印一个特定的 Python 字典键:

I would like to print a specific Python dictionary key:

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

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

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']

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

Is there any name_the_key() method to print a key name?

好的,非常感谢大家的反应!:) 我意识到我的问题没有很好地表述和微不足道.我只是感到困惑,因为我意识到 key_name 和 mydic['key_name'] 是两个不同的东西,我认为从字典上下文中打印 key_name 是不正确的.但确实我可以简单地使用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 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! :)

推荐答案

根据定义,字典具有任意数量的键.没有钥匙".你有 keys() 方法,它给你一个 python list 所有键,你有 iteritems() 方法,它返回键值对,所以

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 版本:

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天全站免登陆