简体   繁体   English

检查字典值是否在字符串中,输出=键

[英]Check if a dictionary value is in a string, output = key

Python 3.4 Python 3.4

Let's say I've got a dictionary: 假设我有字典:

dict = { "one" : ["abcdefg", "hij"], "two" : ["klmnopq"], "three" : ["rstuvwx", "zyx"] }

And I've also got a string: 而且我还有一个字符串:

string = "XXXabcdefgXXXhijXXXXXklmnopqXXXXXXzyxXXXXzyxXXXXX" 

...where "X" stands for other random unimportant letters. ...其中“ X”代表其他随机不重要的字母。

I want to check if the a VALUE of the dictionary is in the string (eg if "hij" can be found in String), and if it is, then I want an output that creates a list of all of the different items found in the string. 我想检查字典中的VALUE是否在字符串中(例如,如果在字符串中可以找到“ hij”),如果是,那么我想要一个输出来创建在其中找到的所有不同项的列表字符串。

Something like this: 像这样:

list = []
if dict.value in string:
    list.append(dict.key)
print(list) --> ["one", "one", "two", "three", "three"]

What would be the best way to get this sort of result? 获得这种结果的最佳方法是什么?

You're very close, you have the logic correct and are just missing the loops. 您的关系非常紧密,逻辑正确,只是缺少循环。

In the outer loop, you need to loop through the keys in the dictionary. 在外部循环中,您需要循环浏览字典中的键。

for key in dict.keys():

In the inner loop, you need to loop through each element in the value list. 在内部循环中,您需要遍历值列表中的每个元素。

for value in dict[key]:

Here is the full code: 这是完整的代码:

key_list = []
for key in dict.keys():
    for value in dict[key]:
        if value in string:
            key_list.append(key)
print(key_list)

One other thing to note is that dictionaries do not hold an order, so your result will not be sorted as you would expect. 需要注意的另一件事是,字典不持有订单,因此您的结果将不会像您期望的那样排序。

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

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