简体   繁体   English

从以列表为值的字典中获取键

[英]Get the key from a dictionary with list as value

Consider the following dictionary.考虑以下字典。

dict = {
    'key_1': ['name1', 'name2', 'name3'],
    'key_2': ['name4', 'name5', 'name6']
}

Given a string called "name6", how to easy figure that this is belongs to "key_2" key with lesser looping.给定一个名为“name6”的字符串,如何轻松确定它属于循环较少的“key_2”键。 I have the following code, how can I optimize for time constraint of this.我有以下代码,如何针对时间限制进行优化。 Above code is just an example, there are several such keys present in the dictionary.上面的代码只是一个例子,字典中有几个这样的键。

dict = {
    'key_1': ['name1', 'name2', 'name3'],
    'key_2': ['name4', 'name5', 'name6']
}

output_key = None

for key in dict:
    if 'name6' in dict[key]:
        output_key = key
        break

In the current form of this dict, you cannot find the key that stores "name6" without iterating over the keys.在此 dict 的当前形式中,如果不迭代键,您将无法找到存储“name6”的键。

You need a different data structure, you can create another dict where the keys are each unique string from the original dict and values are list of keys that hold that string in the original dict, that way you can check for that string in the new dict in O1, and get a list of keys that all contain that string in the old dict.您需要不同的数据结构,您可以创建另一个字典,其中键是原始字典中的每个唯一字符串,值是在原始字典中保存该字符串的键列表,这样您就可以在新字典中检查该字符串在 O1 中,并获取所有包含旧字典中该字符串的键的列表。

The creation of that new dict is O(n) (where n is the number of strings the original dict holds), but since its also the cost of the search you performed, that is still a win, if you need to lookup m values, you has to do O(m*n) before, but after its O(max(m,n))新字典的创建是 O(n) (其中 n 是原始字典保存的字符串数),但由于它也是您执行的搜索的成本,如果您需要查找 m 值,这仍然是一个胜利,您必须在 O(m*n) 之前,但在其 O(max(m,n)) 之后

dictionary = {
'key_1': ['name1', 'name2', 'name3'],
'key_2': ['name4', 'name5', 'name6']
}

new_dict = dict()
for key in dictionary:
    for value in dictionary[key]:
        if value in new_dict:
            new_dict[value].append(key)
        else:
            new_dict[value] = [key]

If you know from the start that each value can only be in one key (in the original dict) there is no need for the lists, but it's nice to have just in case;)如果您从一开始就知道每个值只能在一个键中(在原始字典中),则不需要列表,但最好有以防万一;)

This removes the loop and according to other answers seems to be faster, specially for small dictionaries, but ( disclaimer ) I did not benchmark or perform any performance testing.这消除了循环,并且根据其他答案似乎更快,特别是对于小型词典,但是(免责声明)我没有进行基准测试或执行任何性能测试。 Also if the key is not in the list you'll get an index out of bonds error that you need to handle (or make sure the list returned is not empty, ie there is a result, before accessing element [0] ):此外,如果键不在列表中,您将获得需要处理index out of bonds (或确保返回的列表不为空,即在访问元素[0]之前有结果):

mydict = {
    'key_1': ['name1', 'name2', 'name3'],
    'key_2': ['name4', 'name5', 'name6']
}

output_key = next((mykey for mykey,myval in mydict.items() if 'name6' in myval), None)

print(output_key) # key_2

Edit编辑
Replaced with next to get the first value that matches, or default value ( None ).替换为 next 以获取匹配的第一个值,或默认值 ( None )。

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

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