如何在Python中直接获取字典键作为变量(不是通过从值中搜索)? [英] How can I get dictionary key as variable directly in Python (not by searching from value)?

查看:345
本文介绍了如何在Python中直接获取字典键作为变量(不是通过从值中搜索)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这个基本问题,但是我的搜索并没有改变什么,除了如何获得一个字典的键基于我的价值,我不想使用,因为我只想要的文本/名称的关键和担心如果字典有很多条目,那么通过值搜索可能会最终返回2个或更多个键...我想要做的是这样的:

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries... what I am trying to do is this:

mydictionary={'keyname':'somevalue'}
for current in mydictionary:

   result = mydictionary.(some_function_to_get_key_name)[current]
   print result
   "keyname"

这样做的原因是我将这些打印出来我想使用密钥名称和值来执行此操作

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

我已经看到了下面的方法,但这似乎只是返回密钥的值

I have seen the method below but this seems to just return the key's value

get(key[, default])


推荐答案

您应该使用以下重复键:

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])

这篇关于如何在Python中直接获取字典键作为变量(不是通过从值中搜索)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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