Python: How can I filter a n-nested dict of dicts by leaf value?

2024/10/10 2:22:01

I've got a dict that looks something like this:

d = {'Food': {'Fruit'  : {'Apples'    : {'Golden Del.'  : ['Yellow'],'Granny Smith' : ['Green'],'Fuji'         : ['Red'],    },'Cherries'  : ['Red'],'Bananas'   : ['Yellow'],'Grapes'    : {'Red Grapes'   : ['Red'],'Green Grapes' : ['Green'],  },},'Dessert': {'Baked Ds' : {'Cakes'         : {'Yellow Cake' : ['Yellow'],'Red Velvet'  : ['Red'],},'Cookies'      : ['Yellow'],},},'Steak'  : ['Red'],},'Other': ['Blue'],}

So basically, an n-nested dict, where each value is either another dict or a list containing a single item.

Let's say that I want to filter this by a single list item, say, 'Red' such that the result would be:

d = {'Food': {'Fruit'  : {'Apples'    : {'Fuji'        : ['Red'],    },'Cherries'  : ['Red'],'Grapes'    : {'Red Grapes'  : ['Red'], },},'Dessert': {'Baked Ds' : {'Cakes'        : {'Red Velvet'  : ['Red'],},},},'Steak'  : ['Red'],},}

So that the structure remains the same but everything that doesn't have 'Red' as its list item is removed, all the way up the hierarchy.

Any suggestions? I've messed around with this for a while and came up with this, but it doesn't seem to work:

def filterNestedDict(node, searchItem):if isinstance(node,list):return nodeelse:for key, value in node.iteritems():if isinstance(value,dict) and value is not {}:return {key: filterNestedDict(value,searchItem)}elif searchItem in value:return {key: filterNestedDict(value,searchItem)}return filterNestedDict(bigTree, searchItem)

I suspect it's just an issue of recursion, but any suggestions would be greatly appreciated.

Thanks!

Answer

You were pretty close, this should do the trick for you:

def filter_nested_dict(node, search_term):if isinstance(node, list):if node[0] == search_term:return nodeelse:return Noneelse:dupe_node = {}for key, val in node.iteritems():cur_node = filter_nested_dict(val, search_term)if cur_node:dupe_node[key] = cur_nodereturn dupe_node or None
https://en.xdnf.cn/q/69951.html

Related Q&A

contour plot - clabel spacing

I have trouble with matplotlib / pyplot / basemap. I plot contour lines (air pressure) on a map. I use clabel to show the value of the contour lines. But the problem is: the padding between the value a…

Class-based view has no attribute .as_view() error

Im following this tutorial, trying to make an API for my Products table.Heres my .views/API/apitest.py view:from my_app.views.API.serializers import ProductSerializer from my_app.models import Product …

Ordering query result by numeric strings in django (postgres backend)

I have a table with a name (varchar) field that only holds numeric string and I want to order my queries by this field. But name fields are being ordered by alphabetically but I want them to be ordered…

Resolve argparse alias back to the original command

Im using a subparser/subcommand that has an alias. Im using the dest option for the subparser to store the name of the subcommand so I can get it later.Currently if the subcommands name is reallyLongN…

Django: How do I make fields non-editable by default in an inline model formset?

I have an inline model formset, and Id like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would…

How to store result of an operation (like TOPK) per epoch in keras

I have written a custom layer in keras. in part of this custom layer lets say I have a matrix like this: c = tf.cast(tf.nn.top_k(tf.nn.top_k(n, tf.shape(n)[1])[1][:, ::-1], tf.shape(n)[1])[1][:, ::-1],…

How to start Firefox with with specific profile Selenium Python geckodriver

Here is my code:profile = webdriver.FirefoxProfile(C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kvycjolb.Prdel) driver = webdriver.Firefox(profile)Im not getting any error an…

Beautiful Soup find elements having hidden style

My simple need. How do I find elements that are not visible on the webpage currently? I am guessing style="visibility:hidden" or style="display:none" are simple ways to hide an ele…

Fastest way to extract dictionary of sums in numpy in 1 I/O pass

Lets say I have an array like:arr = np.array([[1,20,5],[1,20,8],[3,10,4],[2,30,6],[3,10,5]])and I would like to form a dictionary of the sum of the third column for each row that matches each value in …

How to group by and dummies in pandas

I have a pandas dataframe: key valA 1A 2B 1B 3C 1C 4I want to get do some dummies like this:A 1100b 1010c 1001