Josh Mitkitzel Josh Mitkitzel - 10 days ago 5
Python Question

How to remove common list elements across multiple lists that are values in a dictionary

Example 1:

dictionary = {'key1':['A','B','C'], 'key2': ['G','A']: 'key3': ['Z','X','U','A']}


Example 2:

dictionary = {'key1':['A','B','C'], 'key2': ['G','A']: 'key3': ['Z','X','U']}


In Example 1: The element 'A' is common in all of the lists that are associated with their respective keys.

In Example 2:

'A' is present in the lists of key1 and key2.

In both examples how do I remove 'A' in the lists where it occurs since its shared with the other lists. In other words how do I ensure that each list has unique values that are not shared with the other lists.

Please tell me a method that does not require importing anything. Efficiency is not the main concern here.

Answer
dictionary = {'key1':['A','B','C'], 'key2': ['G','A'], 'key3': ['Z','X','U','A']}

master_list = []
dictt = {}

for k,val in dictionary.items():
    key_list =[]
    for lst in val:
        for char in lst:
            if char not in master_list:
                master_list.append(char)
                key_list.append(char)
                dictt[k] = key_list

print(dictt)

For words:

dictionary = {'key1':['ABC','BCD','CDE'], 'key2': ['GBF','ABC'], 'key3': ['ZFR','XGQ','CDE','AUI']}

master_list = []
dictt = {}

for k,val in dictionary.items():
    key_list =[]
    for lst in val:
#        for char in lst:
        if lst not in master_list:
            master_list.append(lst)
            key_list.append(lst)
            dictt[k] = key_list

print(dictt)
Comments