我想比较两个字典的键值对。比较的方式是,将第一本字典的第一项与第二本字典的第一项进行比较,将第二项与第二项进行比较,并且像这样进行。
词典的结构是:
dep_feats = {0: {'Gender': {'Masc'}, 'Number': {'Sing'}, 'Person': {'3'}}, 1: {}, 2: {'Number': {'Sing'}, 'Person': {'3'}}, 3: {'Gender': {'Masc'}, 'Number': {'Sing'}, 'Person': {'3'}, 'Tens': {'Past'}, 'Voice': {'Act'}}, 4: {}}
和
head_feats = {0: {'Gender': {'Masc'}, 'Number': {'Sing'}, 'Person': {'3'}, 'Tens': {'Past'}, 'Voice': {'Act'}}, 1: {'Number': {'Sing'}, 'Person': {'3'}}, 2: {'Gender': {'Masc'}, 'Number': {'Sing'}, 'Person': {'3'}, 'Tens': {'Past'}, 'Voice': {'Act'}}, 3: {}, 4: {'Gender': {'Masc'}, 'Number': {'Sing'}, 'Person': {'3'}, 'Tens': {'Past'}, 'Voice': {'Act'}}}
for i in range(len(dep_feats)):
for j in range(len(head_feats)):
if i == j:
if dep_feats[i].items() == head_feats[i].items():
print(dep_feats[i].items())
答案 0 :(得分:0)
我想,如果您要比较同一个键,则应该创建一个包含两个字典中的公共键的集合,然后比较它们的值。
common_keys = set(dep_feats).intersection(set(head_feats))
for key in common_keys:
if dep_feats[key].items() == head_feats[key].items():
print(dep_feats[key])
这样,您将通过删除嵌套的for循环来减少时间复杂度。
答案 1 :(得分:0)
这可以通过zip()
for dep, head in zip(dep_feats.items(), head_feats.items()):
if dep == head:
print(dep)