简体   繁体   English

如何从指定值的字典中获取所有键?

[英]How to get all keys from dictionary that specified values?

If I have dict like this: 如果我有这样的字典:

some_dict = {'a': 1, 'b': 2, 'c': 2}

How to get keys that have values 2, like this: 如何获取具有值2的键,如下所示:

some_dict.search_keys(2)

This is example. 这是一个例子。 Assume some_dict is has many thousands or more keys. 假设some_dict是具有成千上万个或更多的键。

You can do it like this: 您可以这样做:

[key for key, value in some_dict.items() if value == 2]

This uses a list comprehension to iterate through the pairs of (key, value) items, selecting those keys whose value equals 2. 这使用列表推导来遍历(key, value)项对,选择值等于2的那些键。

Note that this requires a linear search through the dictionary, so it is O(n) . 请注意,这需要对字典进行线性搜索,因此它是O(n) If this performance is not acceptable, you will probably need to create and maintain another data structure that indexes your dictionary by value. 如果这种性能不可接受,则可能需要创建和维护另一个按值索引字典的数据结构。

you can also use dictionary comprehension, if you want result to be dictionary 如果您希望结果成为字典,您还可以使用字典理解

{ x:y for x,y in some_dict.items() if y == 2}

output: 输出:

{'c': 2, 'b': 2}

Well, you can use generator to produce found key values, one by one, instead of returning all of them at once. 好了,您可以使用生成器逐个生成找到的键值,而不是一次返回所有键值。

The function search_keys returns generator 函数search_keys返回生成器

def search_keys(in_dict, query_val):
    return (key for key, val in in_dict.iteritems() if val == query_val)

# get keys, one by one
for found_key in search_keys(some_dict, 2):
    print(found_key)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM