Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python字典中基于条件的数据抓取_Python_Python 3.x_Dictionary - Fatal编程技术网

python字典中基于条件的数据抓取

python字典中基于条件的数据抓取,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一本下面这样的字典 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"]} 我想在“匹配”标题下获取键名(其中键的值为match或match2),在“不匹配”标题下获取不匹配的键名 我尝试了以下代码,但

我有一本下面这样的字典

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"]}
我想在“匹配”标题下获取键名(其中键的值为match或match2),在“不匹配”标题下获取不匹配的键名

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

    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

您可以使用
any
进行列表理解,并使用set difference进行成员资格检查和不匹配:

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 

您可以遍历dict项,并测试子dict的任何键中是否有
match
match2

print(*(k for k, s in d.items() if any(w in s for w in ('match', 'match2'))), sep='\n')
print(*(k for k, s in d.items() if all(w not in s for w in ('match', 'match2'))), sep='\n')
这将产生:

key1
key2
key3
key4
类似地,如果
match1
match2
都不在子目录的任何键中,则可以通过测试来获得不匹配的键:

print(*(k for k, s in d.items() if any(w in s for w in ('match', 'match2'))), sep='\n')
print(*(k for k, s in d.items() if all(w not in s for w in ('match', 'match2'))), sep='\n')
这将产生:

key1
key2
key3
key4