基于路径关系重新分配字典的Python程序
给定一个字典,任务是制定一个Python程序,使用它的键和值之间的路径关系重新分配它,即一个键的值是另一个键的键。
例子:
Input : test_dict = {3 : 4, 5 : 6, 4 : 8, 6 : 9, 8 : 10}
Output : {3: 10, 5: 9, 4: 10, 6: 9, 8: 10}
Explanation : key 3 has value 4. key 4 has value 8. key 8 has value 10. there is no key 10 thus in the new dictionary key will have value 10.
Similarly, key 5 has value 6. key 6 has value 9. There is no key 9 hence in the new dictionary key 5 will have value 9.
方法:使用循环和键()
在这里,我们迭代每个键并找到它的深度,通过使用外部函数重复检查每个值是否是字典中其他项目的键。
Python3
def find_depth(ele, dicti):
# finding depth
for idx in range(len(list(dicti.keys()))):
# assigning value as key if found
if ele in list(dicti.keys()):
ele = dicti[ele]
return ele
# initializing dictionary
test_dict = {3: 4, 5: 6, 4: 8, 6: 9, 8: 10}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = dict()
# iterating for each key
for key, val in list(test_dict.items()):
test_dict.pop(key)
res[key] = find_depth(val, test_dict)
# printing result
print("The reassigned dictionary : " + str(res))
输出:
The original dictionary is : {3: 4, 5: 6, 4: 8, 6: 9, 8: 10}
The reassigned dictionary : {3: 10, 5: 9, 4: 10, 6: 9, 8: 10}