首页 > 解决方案 > 根据python字典中的条件抓取数据

问题描述

我有一本像下面这样的字典。

d = {'key1': {'match': '45.56', 'key12': '45.56'},
 'key2': {'key21': '45.56', 'match2': '45.56'},
 'key3': {'key31': '45.56', 'key32': '45.56'},
  'key4': ["key4", "key5"]}

我想在“匹配”标题下获取键名(其中键的值是匹配或匹配2),在“不匹配”标题下获取不匹配的名称。

match
key1
key2

not match
key3
key4

我尝试了以下代码,但它没有返回任何内容:

    d = {'key1': {'match': '45.56', 'key12': '45.56'},
     'key2': {'key21': '45.56', 'match2': '45.56'},
     'key3': {'key31': '45.56', 'key32': '45.56'},
      'key4': ["key4", "key5"]}

print(*[k for k in d if 'match' in d[k] or 'match2' in d[k]], sep='\n')    ---only prints the matched values

标签: pythonpython-3.xdictionary

解决方案


您可以使用集合差异进行列表理解以获取匹配any项和成员资格检查以及不匹配项:

d = {'key1': {'match': '45.56', 'key12': '45.56'},
     'key2': {'key21': '45.56', 'match2': '45.56'},
     'key3': {'key31': '45.56', 'key32': '45.56'},
      'key4': ["key4", "key5"]}

to_look = {'match', 'match2'}

match = [k for k, v in d.items() if any(x in to_look for x in v)]    
not_match = set(d).difference(match)

print('match')
print(*match, sep='\n')
print('\nnot match')
print(*not_match, sep='\n')

输出

match
key1  
key2        

not match       
key3                   
key4 

推荐阅读