如何在 Python 字典中打印给定值的键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15784590/
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 20:59:53  来源:igfitidea点击:

How can you print a key given a value in a dictionary for Python?

pythondictionarykey

提问by Jett

For example lets say we have the following dictionary:

例如,假设我们有以下字典:

dictionary = {'A':4,
              'B':6,
              'C':-2,
              'D':-8}

How can you print a certain key given its value?

给定某个键的值,如何打印它?

print(dictionary.get('A')) #This will print 4

How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.

你怎么能反过来呢?即不是通过引用键来获取值,而是通过引用值来获取键。

采纳答案by SlxS

I don't believe there is a way to do it. It's not how a dictionary is intended to be used... Instead, you'll have to do something similar to this.

我不相信有办法做到这一点。这不是字典的用途...相反,您必须执行与此类似的操作。

for key, value in dictionary.items():
    if 4 == value:
        print key

回答by Inbar Rose

The dictionary is organized by: key -> value

字典按以下方式组织:键 -> 值

If you try to go: value -> key

如果你尝试去: value -> key

Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.

那么你有几个问题;重复,有时字典包含您不希望将其作为键的大(或不可散列)对象。



However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:

但是,如果您仍然想这样做,您可以通过迭代 dicts 键和值并按如下方式匹配它们来轻松实现:

def method(dict, value):
    for k, v in dict.iteritems():
        if v == value:
            yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
    print r

b


As noted in a comment, the whole thing can be written as a generator expression:

正如评论中所指出的,整个事情可以写成一个生成器表达式:

def method(dict, value):
    return (k for k,v in dict.iteritems() if v == value)


Python versions note: in Python 3+ you can use dict.items()instead of dict.iteritems()

Python 版本注意:在 Python 3+ 中,您可以使用dict.items()代替dict.iteritems()

回答by Will Townley

Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.

嘿,我多年来一直被困在这件事上,您所要做的就是将键与值交换,例如

Dictionary = {'Bob':14} 

you would change it to

你会把它改成

Dictionary ={1:'Bob'} 

or vice versa to set the key as the value and the value as the key so you can get the thing you want

反之亦然,将键设置为值,将值设置为键,这样你就可以得到你想要的东西

回答by Fouad Boukredine

In Python 3:

在 Python 3 中:

# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}

# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])

Output:

输出:

Y

回答by boop

target_key = 4
for i in dictionary:
    if dictionary[i]==target_key:
        print(i)

回答by karthik bharadwaj

Within a dictionary if you have to find the KEY for the highest VALUE please do the following :

在字典中,如果您必须找到最高 VALUE 的 KEY,请执行以下操作:

  1. Step 1: Extract all the VALUES into a list and find the Max of list
  2. Step 2: Find the KEY for the particular VALUE from Step 1
  1. 步骤 1:将所有 VALUES 提取到列表中并找到列表的最大值
  2. 第 2 步:从第 1 步中找到特定 VALUE 的 KEY

The visual analyzer of this code is available in this link : LINK

此代码的可视化分析器可在此链接中找到:LINK

    dictionary = {'A':4,
              'B':6,
              'C':-2,
              'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
    if val == max(lis) :
        print("The highest KEY in the dictionary is ",key)