如果给定的字符串与字典中的键值匹配,如何返回键 [英] How to return key if a given string matches the keys value in a dictionary

查看:341
本文介绍了如果给定的字符串与字典中的键值匹配,如何返回键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是词典的新手,我试图找出如果给定的字符串与字典中的键值匹配则如何返回键.

I am new to dictionaries, and i'm trying to find out how to return a key if a given string matches the keys value in a dictionary.

示例:

dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}

如果键的值包含blue,我想返回colorsomeothercolor.

I want to return color and someothercolor, if the key's value contains blue.

有什么建议吗?

推荐答案

您可以将 list comprehension 表达式写为:

>>> my_dict = {"color": ("red", "blue", "green"), "someothercolor": ("orange", "blue", "white")}

>>> my_color = "blue"
>>> [k for k, v in my_dict.items() if my_color in v]
['color', 'someothercolor']

注意:请勿使用dict作为变量,因为 dict 是Python中的内置数据类型

Note: Do not use dict as variable because dict is built-in data type in Python

这篇关于如果给定的字符串与字典中的键值匹配,如何返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆