I have generated a nested dictionary as a JSON which includes a concept, and then a reference to that concept in a sentence scraped from a website or a different JSON known as "ALTERNATIVE" with an associated superclass (please see hyperlink and below for actual minimum viable example):
"Glide": {"superclasses": {"Entity": [{"source": "ALTERNATIVE"}]}}, "Yacht": {"superclasses": {"Boat": [{"reference": "Originally, yachts were sailing-boats, but now there are also motor yachts.", "source": "https://simple.wikipedia.org/wiki/Yacht"}, {"reference": "A yacht is a type of boat which is mainly used for recreation.", "source": "https://simple.wikipedia.org/wiki/Yacht"}], "Vessel": [{"reference": "In sailboat racing, a yacht is any sailing vessel taking part in a race.", "source": "https://simple.wikipedia.org/wiki/Yacht"}]}}, "Yam": {"superclasses": {"Vegetable": [{"reference": "A yam is a root vegetable.", "source": "https://simple.wikipedia.org/wiki/Yam"}, {"reference": "Yam is a vegetable that can be cooked in many ways.", "source": "https://simple.wikipedia.org/wiki/Yam"}], "Name": [{"reference": "Yam is the common name for some species in the genus Dioscorea. ", "source": "https://simple.wikipedia.org/wiki/Yam"}]}},
What I'd like to do for a key in my nested dictionary (e.g. "Yacht") is to look through its "superclasses" (e.g. in this case "Boat" and "Vessel") and see whether or not they are keys in my nested dictionary.
Currently I've converted my nested dictionary to a list of tuples of the form "(key, superclass)" that is ordered in terms of how many superclasses each key has (in descending order) to make things easier.
import json
from nltk.corpus import wordnet as wn
## importing the nested dictionary
tax = json.load(open("data/nested_dict.json"))
## Converting our nested dictionary into a list of tuples
tax_list = [(key, value) for key, value in tax.items()]
## Sorting out list with tuples in descending order of how many superclasses they have
tax_list.sort(key=lambda x: len(x[1]["superclasses"].keys()), reverse = True)
Thanks,
Mark
question from:
https://stackoverflow.com/questions/65891118/how-to-select-elements-in-a-nested-dictionary-and-delete-them-recursively 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…