Let's assume I have a dictionary looks like this, where every instance of bakery_items
will contain key-value pairs, of which the value is a dictionary itself:
{ "bakery_items" : {"pie":{"iscake" : "no", "edible" : "yes"}, "cheesecake":{"iscake" : "yes", "edible" : "yes"}, "shoe":{"iscake" : "no", "edible" : "no"}}
"key1" : "blah",
"key2" : "blah blah",
"nestedlist" : [
{ "bakery_items" : {"potato":{"iscake" : "no", "edible" : "yes"}, "pound_cake":{"iscake" : "yes", "edible" : "yes"}, "scale":{"iscake" : "no", "edible" : "no"}},
"nestednestedlist" : [
{ "bakery_items" : {"pomegranate":{"iscake" : "no", "edible" : "yes"}, "sponge_cake":{"iscake" : "yes", "edible" : "yes"}, "sandal":{"iscake" : "no", "edible" : "no"}},
"keyA" : "blah blah blah" },
{ "bakery_items" : {"pickle":{"iscake" : "no", "edible" : "yes"}, "red_velvet":{"iscake" : "yes", "edible" : "yes"}, "screwdriver":{"iscake" : "no", "edible" : "no"}},
"keyZ" : "blah blah blah" }],
"anothernestednestedlist" : [
{ "bakery_items" : {"pizza":{"iscake" : "no", "edible" : "yes"}, "fruitcake":{"iscake" : "yes", "edible" : "yes"}, "scissor":{"iscake" : "no", "edible" : "no"}},
"keyQ" : "blah blah" },
{ "bakery_items" : {"plum":{"iscake" : "no", "edible" : "yes"}, "pancake":{"iscake" : "yno", "edible" : "yes"}, "scratchpad":{"iscake" : "no", "edible" : "no"}},
"keyW" : "blah" }] } ] }
I am able to find the bakery_items
as a list thanks to this answer to this question, but assume I don't need details about non-cake items (i.e bakery_items
will only include key-value pairs that have iscake
as yes
). The final result should look like this:
{ "bakery_items" : {"cheesecake":{"iscake" : "yes", "edible" : "yes"}}
"key1" : "blah",
"key2" : "blah blah",
"nestedlist" : [
{ "bakery_items" : {"pound_cake":{"iscake" : "yes", "edible" : "yes"}},
"nestednestedlist" : [
{ "bakery_items" : {"sponge_cake":{"iscake" : "yes", "edible" : "yes"}},
"keyA" : "blah blah blah" },
{ "bakery_items" : {"red_velvet":{"iscake" : "yes", "edible" : "yes"}},
"keyZ" : "blah blah blah" }],
"anothernestednestedlist" : [
{ "bakery_items" : {"fruitcake":{"iscake" : "yes", "edible" : "yes"}},
"keyQ" : "blah blah" },
{ "bakery_items" : {},
"keyW" : "blah" }] } ] }
How can I make sure I find all occurrences bakery_items
in such a nested structure, and at the same time make it so that I only have items that are cakes?
NOTE: The example is based on the example given by Matt Swain in this question. I am using Python 3.x if it matters.