crashwap
crashwap

Reputation: 3062

Python delete dictionary items with same values

How would I remove dictionary items that have different keys but identical values? I am sure there a better way than my novice algorithm...?

Example: (abends with error "dictionary changed size during iteration")

The goal of this example is to remove either 'car_id' or 'truck_id' from dict.

key_fields_obj = {}
key_fields_obj['car_id'] = 'bob'
key_fields_obj['bike_id'] = 'sam'
key_fields_obj['truck_id'] = 'bob' #goal: remove this one, so left with only car_id and bike_id

for item in key_fields_obj:
    tst = key_fields_obj[item]
    for comp in key_fields_obj:
        if item == comp:
            continue
        cmp = key_fields_obj[comp]
        if cmp == tst:
            del key_fields_obj[comp]

print(key_fields_obj)

Upvotes: 0

Views: 69

Answers (2)

Supratim Haldar
Supratim Haldar

Reputation: 2416

Create a new dict with values as key and key as values, then perform the same again on new dict.

>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'bob': 'truck_id', 'sam': 'bike_id'}
>>>
>>> key_fields_obj = {key_fields_obj[key]: key for key in key_fields_obj}
>>> key_fields_obj
{'truck_id': 'bob', 'bike_id': 'sam'}

Upvotes: 3

jsbueno
jsbueno

Reputation: 110261

seem_values = set()

for key, value in list(key_fields_obj.items()):
   if value in seem_values:
       del key_fields_obj[key]
   else:
       seem_values.add(value)

Upvotes: 2

Related Questions