根据值在多维字典中查找键 [英] Find keys in multidimensional dict based on value
本文介绍了根据值在多维字典中查找键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面这样的字典:
I have a dict of dicts that looks like the following:
{ 'a':{'foo': True,
'bar': 1,
'baz': 'abc'},
'b':{'foo': True,
'bar': 21,
'baz': 'abc'},
'c':{'foo': True,
'bar': 3,
'baz': 'cba'}}
最简单的方法是将dict过滤为仅包含其'baz'的子值为'abc'的那些键?因此,在上面的示例中,它将返回一个类似以下内容的字典:
What is the most efficient way to filter the dict to only include those keys whose sub-values for 'baz' are 'abc'? So in the example above, it would return a dict that looked like:
{ 'a':{'foo': True,
'bar': 1,
'baz': 'abc'},
'b':{'foo': True,
'bar': 21,
'baz': 'abc'}}
推荐答案
{k: v for k, v in my_dict.items() if v['baz'] == 'abc'}
这篇关于根据值在多维字典中查找键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文