簡體   English   中英

創建一個通過詢問某些值來過濾嵌套字典的函數

[英]Creating a function that filters a nest dictionary by asking certain values

我是python的初學者,嘗試創建一個函數,該函數通過在字典中詢問多個值(例如

filtered_options = {'a': 5, 'b': "Cloth'}

對於我的字典

my_dict = {1.0:{'a': 1, 'b': "Food', 'c': 500, 'd': 'Yams'},
           2.0:{'a': 5, 'v': "Cloth', 'c': 210, 'd': 'Linen'}}

如果我在帶有此類選項的過濾器函數中輸入字典,我應該會得到類似

filtered_dict(my_dict, filtered_options = {'a': 5, 'b': "Cloth'}) 

在我的字典中輸出第二個鍵和其他具有相同過濾選項的鍵。

這應該做您想要的。

def dict_matches(d, filters):
    return all(k in d and d[k] == v for k, v in filters.items())

def filter_dict(d, filters=None):
    filters = filters or {}
    return {k: v for k, v in d.items() if dict_matches(v, filters)}

測試時會發生以下情況:

>>> filters = {'a': 5, 'b': 'Cloth'}
>>> my_dict = {
...     1.0: {'a': 1, 'b': 'Food', 'c': 500, 'd': 'Yams'},
...     2.0: {'a': 5, 'b': 'Cloth', 'c': 210, 'd': 'Linen'}
... }
>>> filter_dict(my_dict, filters)
{2.0: {'b': 'Cloth', 'a': 5, 'd': 'Linen', 'c': 210}}

你可以這樣做 :

import operator
from functools import reduce

def multi_level_indexing(nested_dict, key_list):
    """Multi level index a nested dictionary, nested_dict through a list of keys in dictionaries, key_list
    """
    return reduce(operator.getitem, key_list, nested_dict)

def filtered_dict(my_dict, filtered_options):
    return {k : v for k, v in my_dict.items() if all(multi_level_indexing(my_dict, [k,f_k]) == f_v for f_k, f_v in filtered_options.items())}

以便:

my_dict = {1.0:{'a': 1, 'b': 'Food', 'c': 500, 'd': 'Yams'},
           2.0:{'a': 5, 'b': 'Cloth', 'c': 210, 'd': 'Linen'}}

會給你:

print(filtered_dict(my_dict, {'a': 5, 'b': 'Cloth'}))  
# prints {2.0: {'a': 5, 'b': 'Cloth', 'c': 210, 'd': 'Linen'}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM