BeeGee BeeGee - 10 months ago 32
Python Question

Remove values from lists of values in a dictionary

I am using Python 2.7 with Windows 7.

I have a dictionary and would like to remove values that correspond to (key, value) pairs from another dictionary.

For example, I have a dictionary

. I would like to remove corresponding (key,value) pairs that are in the dictionary
so that I end up with dictionary

t_dict = {
'a': ['zoo', 'foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee', 'dol', 'bar']

values_to_remove = {
'a': ['zoo'],
'b': ['dol', 'bar']

# remove values here

print final_dict
'a': ['foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee']

I have looked at similar pages on SO and the python dictionaries doc but cannot find anything to solve this specific problem:

How to remove dictionaries with duplicate values from a nested dictionary

How to remove a key from a dictionary?


There cannot be duplicate values in
per key. For example there will never be

t_dict['a'] = ['zoo','zoo','foo','bar']


Since duplicates aren't possible, it might make sense to store the values as a set, not a list. If you can use a set for t_dict, the removal process is both faster and simpler to write (even faster if values_to_remove uses set or frozenset too):

for k, toremove in values_to_remove.viewitems():
    t_dict.get(k, set()).difference_update(toremove)

Use the above if values_to_remove expected to be small, or if t_dict is smaller, you could switch to the following to avoid the temporary set()s (the empty tuple is a singleton, so it costs nothing to use it with dict.get):

for k, v in t_dict.viewitems():
    v.difference_update(values_to_remove.get(k, ()))