目前,我正在创建两个列表,并比较它们是否重复。 取而代之的是,我想从字典中递归地删除嵌套项目 我的问题是,在执行此递归时,如何选择一个深度嵌套的项并更改字典? 当前功能: ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我已经生成了一个嵌套字典作为 JSON ,其中包含一个概念,然后在从网站或不同的 JSON (称为“ALTERNATIVE”)抓取的句子中引用该概念,并具有关联的超类(请参阅超链接和下面的实际最小值可行的例子):
"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"}]}},
我想为嵌套字典中的键(例如“Yacht”)做的是查看它的“超类”(例如在本例中为“Boat”和“Vessel”)并查看它们是否是键我的嵌套字典。
目前,我已将嵌套字典转换为“(键,超类)”形式的元组列表,该列表按照每个键有多少超类(按降序排列)进行排序,以使事情变得更容易。
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)
谢谢,
标记
# Get all Keys in Master Dictionary and Convert to a LIST
allKeys = tax.keys()
allkeys = list(allkeys) # Convert to a 'list' data structure so you can check it in one line of code (see below)
# I assume you want the user to specify the key in question
myKey = input("Please input key: ")
# Get the Superclass Dictionary Associated with that Specific Key
superClassDictionary = tax[myKey]
# Iterate through the Keys in the superClassDictionary
for superclass in superClassDictionary.keys():
if superclass in allKeys:
print("Superclass {} of key {} is also a key in the master dictionary".format(superclass, myKey))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.