nowhereman
nowhereman

Reputation: 82

Remove element from list if it's a value of a key more than once

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

Answers (2)

nowhereman
nowhereman

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

pho
pho

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']

    • Iterate over each element v of `value:
    • If mydict contains the key v,
      • Check if the list at mydict[v] contains key.
      • If it doesn't, add the element v to a new_list
      • If it does, skip adding v
    • Set 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

Related Questions