开发者

Find keys in multidimensional dict based on value

开发者 https://www.devze.com 2023-03-15 12:53 出处:网络
I have a dict of dicts that looks like the following: { \'a\':{\'foo\': True, \'bar\': 1, \'baz\': \'abc\'},开发者_运维技巧

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'}}

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'}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号