Reputation: 82
So, the problem was hard to condense into the title but here's a detailed explanation.
I have a large dictionary that has thousands of key-value pairs that could have the example below:
dict = {'apple' : ['mint', 'nutmeg', 'cinnamon'], 'mint' : ['apple', 'orange', 'banana']}
Notice how the 'apple' is a key and it has the list as its value, and the list contains the 'mint' element.
Somewhere in my large dictionary 'mint' could also be a key and it could have a list of fruits that has the element 'apple'. As it's the keys in the second element of the dictionary.
The issue is I want to keep the pair of apple and mint, no matter which one is the key or not, but I want a refined dictionary where they're not forming duplicates.
So the desired dictionary is either:
dict_2 = {'apple' : ['mint', 'nutmeg', 'cinnamon'], 'mint' : ['orange', 'banana']}
where the 'apple' element from the list of 'mint' has been removed,
or
dict_2 = {'apple' : ['nutmeg', 'cinnamon'], 'mint' : ['apple', 'orange', 'banana']}
where the 'mint' element from the list of 'apple' has been removed.
EDIT: I've found the solution to this problem. You can find it below
Upvotes: 1
Views: 82
Reputation: 82
Code below solves the problem. If anyone would like to show off by making a fancy one-liner, feel free to do so :)
for key, value in my_dict.items(): # iterate over each key, value
for v in value:
if v in my_dict.keys() and key in my_dict[v]:
my_dict[v].remove(key)
else:
continue
Upvotes: 1
Reputation: 25490
mydict = {'apple' : ['mint', 'nutmeg', 'cinnamon'], 'mint' : ['apple', 'orange', 'banana']}
Since this looks like homework and you haven't shown any work or asked a specific question, I'm going to give you hints for the algorithm, but writing the code is up to you.
You want to
Iterate over each key, value
in the dictionary
e.g. key = "apple"; value = ['mint', 'nutmeg', 'cinnamon']
v
of `value:mydict
contains the key v
,
mydict[v]
contains key
.v
to a new_list
v
mydict[key]
to the newly created new_list
Translating this to code is pretty easy, and you can even write this as a cool two-liner. If you run into problems and have a specific question, feel free to ask!
After running my code for this algorithm on mydict
, I get:
{'apple': ['nutmeg', 'cinnamon'], 'mint': ['apple', 'orange', 'banana']}
Upvotes: 1