簡體   English   中英

如何在 Python 的字典中打印給定值的鍵?

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

例如,假設我們有以下字典:

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

給定它的值,如何打印某個鍵?

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

你怎么能倒着做呢? 即不是通過引用鍵來獲取值,而是通過引用值來獲取鍵。

我不相信有辦法做到這一點。 這不是字典的使用方式......相反,您必須做類似的事情。

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

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

輸出:

Y

字典的組織方式是:key -> value

如果你嘗試去:值 -> 鍵

然后你有一些問題; 重復,有時字典包含您不希望將其作為鍵的大型(或不可散列的)對象。


但是,如果您仍然想這樣做,您可以通過迭代 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

正如評論中所指出的,整個事情可以寫成一個生成器表達式:

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

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

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

如果您必須在字典中找到最高 VALUE 的 KEY,請執行以下操作:

  1. 步驟 1:將所有 VALUES 提取到一個列表中並找到列表的最大值
  2. 第 2 步:從第 1 步中找到特定 VALUE 的 KEY

此代碼的可視化分析器可在此鏈接中找到: 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)

我認為如果您使用該值在字典中的位置,這會更容易。

dictionary = {'A':4,
              'B':6,
              'C':-2,
              'D':-8}
 
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
 
# print key with val 4
position = val_list.index(4)
print(key_list[position])
 
# print key with val 6
position = val_list.index(6)
print(key_list[position])
 
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])

嘿,我被這個問題困擾了很久,你所要做的就是用值交換密鑰,例如

Dictionary = {'Bob':14} 

你會把它改成

Dictionary ={1:'Bob'} 

反之亦然,將鍵設置為值,將值設置為鍵,這樣你就可以得到你想要的東西

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM