📜  Python - 解决字典中的传递性

📅  最后修改于: 2022-05-13 01:55:22.052000             🧑  作者: Mango

Python - 解决字典中的传递性

有时,在使用Python字典时,我们可能会遇到需要解决悬空传递性的问题,即删除具有类型a->b、b->c = a->c的关系的键,删除不需要的“b” ”在这种关系中。这种问题可能出现在许多核心 CS 主题中,也可能出现在 Web 开发领域或图形中。让我们讨论可以执行此任务的特定方式。

方法:使用反向字典+循环
这是可以解决此问题的一种方式。在此,我们构建了反向字典,然后运行循环来检查重复项并执行删除。

# Python3 code to demonstrate working of 
# Resolve Transitivity in Dictionary
# Using reverse dictionary + loop
  
# initializing dictionary
test_dict = {'a' : 3, 'b' : 4, 3 : 5, 'l' : 7, 4 : 'd', 7 : 'k'}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Resolve Transitivity in Dictionary
# Using reverse dictionary + loop
temp = {val: key for key, val in test_dict.items()}
for val in temp:
    if val in test_dict:
       test_dict.pop(temp[val])
       test_dict[temp[val]] = test_dict[val]
       test_dict.pop(val)
      
# printing result 
print("The resolved dictionary : " + str(test_dict)) 
输出 :
The original dictionary : {3: 5, 4: 'd', 7: 'k', 'b': 4, 'l': 7, 'a': 3}
The resolved dictionary : {'b': 'd', 'l': 'k', 'a': 5}