[英]How do i compare items in a python LIST to DICTIONARY keys and then construct a dictionary with all elements of the LIST
[英]filtering the keys of a python dictionary for all the items of a list
我正在嘗試過濾特定字符串的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}
您需要檢查all
子字符串是否都在dict鍵中。
您正在檢查每個鍵中是否都包含1
或 ca
,所以您都得到了'bus 1'
因為"1"
顯然是一個子字符串。
if all(a in k for a in spl)
檢查來自拆分輸入字符串的每個子字符串是否等於或等於鍵字符串的子字符串。
我還更改了代碼,以使用小寫字母和帶下划線的單獨單詞,這使您的代碼更具可讀性,並符合pep8樣式指南。
您可以使用以下命令檢查字符串是否包含子字符串中的每個字符:
all(character in somestring for character in substring)
所以,
def filterDictionary(filterdata):
dictionaryToFilter = {'car 1': 100, 'car 2': 200, 'car 3': 300,
'bus 1': 1000, 'bus 2': 2000, 'bus 3': 3000}
return {k: v for (k, v) in dictionaryToFilter.items()
if all(character in k for character in filterdata)}
print(filterDictionary("cr1"))
{'car 1': 100}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.