简体   繁体   English

在列表中搜索一个值并在 python 字典中找到它的键

[英]search a value inside a list and find its key in python dictionary

suppose the dictionary contains a list like this and I want to find if "name" exists in the dictionary then find its key in python..... anyone can help?假设字典包含一个这样的列表,我想查找字典中是否存在“名称”,然后在 python 中找到它的键......任何人都可以帮忙吗?

test_dict = { "what is your name" :['name',"what's your name",'tell me your name ?'],
              "time" : ['time','whats the time'] }

so the expected output of search 'name' would look like 'what is your name' !所以搜索 'name' 的预期输出看起来像 'what is your name' !

You only need acomprehension list , like this:你只需要一个理解列表,像这样:

test_dict = { "what is your name" :['name',"what's your name",'tell me your name ?'],
              "time" : ['time','whats the time'] }

results = [k for k,v in test_dict.items() if "name" in v]

You only need a [comprehension list][1], like this: (fixed)你只需要一个[理解列表][1],像这样:(固定)

test_dict = { "what is your name" :['name',"what's your name",'tell me your name ?'],"time" : ['time','whats the time'] }
for t_d in test_dict:
    results = [k for k,v in t_d.items() if "name" in v]

print("100"*100)
print(results)
print("100"*100)

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

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