我正在尝试过滤 python 字典的键以查找特定字符串。
def filterDictionary(filterdata):
dictionaryToFilter = {'car 1':100,'car 2': 200, 'car 3':300, 'bus 1':1000, 'bus 2':2000, 'bus 3':3000}
filterInput =[]
filterInput = filterdata.split()
for a in filterInput:
dictonaryFiltered = {k:v for (k,v) in dictionaryToFilter.items() if a in k}
return dictonaryFiltered
我已经到了这样的地步:我的代码过滤输入的任何字符串的键,并用空格分隔,但我想让它过滤所有字符串。
例如filterDictionary('ca 1')将返回{'car 1': 100, 'bus 1': 1000} 我希望它只返回 {'car 1': 100}。
我猜它是使用 all() 完成的,但我无法弄清楚。
谢谢。
最佳答案
def filter_dictionary(filter_data):
dictionary_to_filter = {'car 1': 100, 'car 2': 200, 'car 3': 300, 'bus 1': 1000, 'bus 2': 2000, 'bus 3': 3000}
spl = filter_data.split()
dictionary_filtered = {k: v for (k, v) in dictionary_to_filter.items() if all(a in k for a in spl)}
return dictionary_filtered
print(filter_dictionary('ca 1') )
{'car 1': 100}
您需要检查所有
子字符串是否都在 dict 键中。
您正在检查每个键中是否有 1
或 ca
而非两者,因此您会得到'bus 1'
因为 "1"
显然是一个子字符串。
if all(a in k for a in spl)
检查分割输入字符串中的每个子字符串是否等于或键字符串的子字符串。
我还更改了您的代码以使用小写字母并使用下划线分隔单词,这使您的代码更具可读性并符合 pep8风格指南。
关于python - 过滤Python字典的键以查找列表中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395004/