如何直接在 Python 中将字典键作为变量获取(而不是通过从值中搜索)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3545331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:23  来源:igfitidea点击:

How can I get dictionary key as variable directly in Python (not by searching from value)?

pythondictionarykey

提问by Rick

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:

很抱歉这个基本问题,但我对此的搜索除了如何根据字典的值获取字典的键之外没有发现任何其他内容,我不想使用它,因为我只想要键的文本/名称并且我担心搜索如果字典有很多条目,按值可能最终返回 2 个或更多键......我想要做的是:

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

采纳答案by systempuntoout

You should iterate over keys with:

您应该使用以下方法迭代键:

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

回答by Escualo

If you want to print key and value, use the following:

如果要打印键和值,请使用以下命令:

for key, value in my_dict.iteritems():
    print key, value

回答by Manoj Govindan

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

这样做的原因是我将这些打印到文档中,并且我想在执行此操作时使用键名和值

Based on the above requirement this is what I would suggest:

基于上述要求,这是我的建议:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))

回答by kurian

keys=[i for i in mydictionary.keys()]or keys = list(mydictionary.keys())

keys=[i for i in mydictionary.keys()]或者 keys = list(mydictionary.keys())

回答by splucena

Iterate over dictionary (i) will return the key, then using it (i) to get the value

迭代字典 (i) 将返回键,然后使用它 (i) 获取值

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

回答by Sudhin

If the dictionary contains one pair like this:

如果字典包含这样的一对:

d = {'age':24}

then you can get as

那么你可以得到

field, value = d.items()[0]

For Python 3.5, do this:

对于 Python 3.5,请执行以下操作:

key = list(d.keys())[0]

回答by siddharth

For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

对于 python 3,如果您只想获取密钥,请使用它。如果需要值,请将 print(key) 替换为 print(values)。

for key,value in my_dict:
  print(key)

回答by Libert

As simple as that:

就如此容易:

mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]

You will modify your dictionary and should make a copy of it first

您将修改您的字典,并应先制作一份副本

回答by s3icc0

What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.

我有时会创建另一个字典,以便能够以字符串形式访问我认为需要的任何内容。然后我遍历多个匹配键的字典来构建例如一个以第一列作为描述的表。

dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1} 

for key, value in dict_names.items():
    print('{0} {1}'.format(dict_names[key], dict_values[key])

You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)

您可以轻松地使用大量字典来匹配数据(我喜欢这样一个事实,即使用字典您总是可以引用众所周知的键名)

yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.

是的,我使用字典来存储函数的结果,所以我不需要每次只调用它们一次就运行这些函数,然后随时访问结果。

EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same

编辑:在我的示例中,键名并不重要(我个人喜欢使用相同的键名,因为从任何匹配的字典中选择一个值更容易),只需确保每个字典中的键数是相同

回答by Georg

You could simply use *which unpacks the dictionary keys. Example:

您可以简单地使用*which 解压字典键。例子:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')