Home > Net >  removing all the keys with the same value in dictionary
removing all the keys with the same value in dictionary

Time:02-26

I want to get a new dictionary by removing all the keys with the same value (keys are differents, values are the same)

For example: Input:

dct = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}

expected output:

 {'key2': [1, 2, 6]}

key1 and key3 was deleted because they shared same values.

I have no idea about it?

CodePudding user response:

You can do this by creating a dictionary based on the values. In this case the values are lists which are not hashable so convert to tuple. The values in the new dictionary are lists to which we append any matching key from the original dictionary. Finally, work through the new dictionary looking for any values where the list length is greater than 1 - i.e., is a duplicate. Then we can remove those keys from the original dictionary.

d = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}

control = {}

for k, v in d.items():
    control.setdefault(tuple(v), []).append(k)

for v in control.values():
    if len(v) > 1:
        for k in v:
            del d[k]

print(d)

Output:

{'key2': [1, 2, 6]}

CodePudding user response:

I created a list of counts which holds information about how many times an item is in the dictionary. Then I copy only items which are there once.

a = {"key1": [1,2,3], "key2": [1,2,6], "key3": [1,2,3]}

# find how many of each item are there
counts = list(map(lambda x: list(a.values()).count(x), a.values()))
result = {}

#copy only items which are in the list once
for i,item in enumerate(a):
    if counts[i] == 1:
        result[item] = a[item]

print(result)

CodePudding user response:

One loop solution:

dict_ = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}

key_lookup = {}
result = {}
for key, value in dict_.items():
    v = tuple(value)
    if v not in key_lookup:
        key_lookup[v] = key
        result[key] = value
    else:
        if key_lookup[v] is not None:
            del result[key_lookup[v]]
            key_lookup[v] = None

print(result)

Output:

{'key2': [1, 2, 6]}

CodePudding user response:

As given by the OP, the simplest solution to the problem:

dct = {'key1' : [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}

print({k:v for k, v in dct.items() if list(dct.values()).count(v) == 1})

Output:

{'key2': [1, 2, 6]}
  • Related