在python中如何通过键的值访问键

在python中如何通过键的值访问键,python,dictionary,Python,Dictionary,我想知道,有没有一种方法可以让我通过知道它的价值来得到一把钥匙?例如,一个代码,这样您就可以通过按其值查找键来添加零件 ww = "the quick brown fox jumps over the lazy dog." counts = dict() words = ww.split() val = [] for word in words: if word in counts: counts[word] += 1 else:

我想知道,有没有一种方法可以让我通过知道它的价值来得到一把钥匙?例如,一个代码,这样您就可以通过按其值查找键来添加零件

ww = "the quick brown fox jumps over the lazy dog."
counts = dict()
words = ww.split()
val = []
for word in words:
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1


for keys, values in counts.items():
    val.append(int(values))

下面是添加单词的代码,以及我们可以在代码中遇到它多少次。

您可以为此创建一个函数:

def get_key_by_value(dictionary, value):
    for k, v in dictionary.items():
        if v == value:
            return k
    return None

test_dict = {"one": "two", "two": "three"}
print(get_key_by_value("two")) # "one"
注意:此函数仅返回第一个值-由于这是一个无序的
dict
,因此它可能会使用给定的值指定任何键。要解决此问题,可以将所有结果添加到列表中:

def get_keys_by_value(dictionary, value):
    result = []
    for k, v in dictionary.items():
        if v == value:
            result.append(k)
    return result

test_dict = {"one": "two", "two": "three"}
print(get_keys_by_value("two")) # ["one"]

你的问题到底是什么?不是直接的。你需要在键/值对之间循环,找到具有给定值的键。那么我该怎么做呢?@MarkMeyer是询问他们是否可以访问已知值的键的人?如果我们有两个相等的值呢?@juststart你是什么意思?您已经在显示的代码中这样做了。谢谢,这正是我想要的