Removing duplicates in dictionary values ​​in python

Sorry, the topic title is fuzzy, it's hard for me to explain.

I have a dictionary in which each value is a list of items. I want to remove duplicate elements so that each element appears in the lists at least once (preferably once).

Consider the dictionary:

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]}

'weapon2' and 'weapon3' have the same meaning, so this should result in:

result_dictionary = {"weapon1":[1],"weapon2":[3],"weapon3":[2]}

since I do not mind order, this can also lead to:

result_dictionary = {"weapon1":[1],"weapon2":[2],"weapon3":[3]}

But when “no choice”, he must leave the meaning. Consider this new dictionary:

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3],"weapon4":[3]}

now, since he cannot assign "2" or "3" only once, without leaving the key blank, a possible output would be:

result_dictionary = {"weapon1":[1],"weapon2":[3],"weapon3":[2],"weapon4":[3]}

,

+4
3
#!/usr/bin/env python3

example_dictionary = {"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]}

result = {}
used_values = []

def extract_semi_unique_value(my_list):
    for val in my_list:
        if val not in used_values:
            used_values.append(val)
            return val
    return my_list[0]

for key, value in example_dictionary.items():
    semi_unique_value = extract_semi_unique_value(value)
    result[key] = [semi_unique_value]

print(result)
+1

, , . , .

itertools.product(), . ( ).

from itertools import product
def dedup(weapons):
    # get the keys and values ordered so we can join them back
    #  up again at the end
    keys, vals = zip(*weapons.items())

    # because sets remove all duplicates, whichever combo has
    #  the longest set is the most unique
    best = max(product(*vals), key=lambda combo: len(set(combo)))

    # combine the keys and whatever we found was the best combo
    return {k: [v] for k, v in zip(keys, best)}

:

dedup({"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3]})
#: {'weapon1': 1, 'weapon2': 2, 'weapon3': 3}
dedup({"weapon1":[1,2,3],"weapon2":[2,3],"weapon3":[2,3],"weapon4":[3]})
#: {'weapon1': 1, 'weapon2': 2, 'weapon3': 2, 'weapon4': 3}
0

this can help

import itertools
res = {'weapon1': [1, 2, 3], 'weapon2': [2, 3], 'weapon3': [2, 3]}
r = [[x] for x in list(set(list(itertools.chain.from_iterable(res.values()))))]
r2 = [x for x in res.keys()]
r3 = list(itertools.product(r2,r))
r4 = dict([r3[x] for x in range(0,len(r3)) if not x%4])
0
source

Source: https://habr.com/ru/post/1691255/


All Articles