从字典中删除重复性的Python程序
给定一个值作为列表的字典,任务是编写一个Python程序,该程序可以删除字典的内容,而不管它们是多次出现的键或值。
Input : {‘gfg’ : [‘gfg’, ‘is’, ‘best’], ‘best’ : [‘gfg’], ‘apple’ : [‘good’]}
Output : {‘gfg’: [‘gfg’, ‘is’, ‘best’], ‘apple’: [‘good’]}
Explanation : best key is omitted as it is already as value of 1st key.
Input : {‘gfg’ : [‘gfg’, ‘is’, ‘best’, ‘apple’], ‘best’ : [‘gfg’], ‘apple’ : [‘good’]}
Output : {‘gfg’: [‘gfg’, ‘is’, ‘best’, ‘apple’]}
Explanation : best and apple keys are omitted as it is already as value of 1st key.
方法:使用循环和items()
在这种情况下,我们迭代每个键,并使用 items() 提取其值,并记住它们,如果键和值已经发生,则省略添加/创建。
程序:
Python3
# initializing dictionary
test_dict = {'gfg': ['gfg', 'is', 'best'],
'best': ['gfg'],
'apple': ['good']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = dict()
for key, val in test_dict.items():
flag = True
for key1, val1 in res.items():
# filtering value from memoised values
if key in val1:
flag = False
if flag:
res[key] = val
# printing result
print("The filtered dictionary : " + str(res))
输出:
The original dictionary is : {‘gfg’: [‘gfg’, ‘is’, ‘best’], ‘best’: [‘gfg’], ‘apple’: [‘good’]}
The filtered dictionary : {‘gfg’: [‘gfg’, ‘is’, ‘best’], ‘apple’: [‘good’]}