[Tutor] Removing values from a dictionary if they are present in a list

Peter Otten __peter__ at web.de
Fri Apr 1 14:49:26 CEST 2011


Steven D'Aprano wrote:

> b = set(B)
> for key, values in A.items():
>     A[key] = list( set(values).difference(b) )
> 
> 
> For Python 3, you will need to change the call A.items() to
> list(A.items()), but otherwise they should be the same.

The documentation doesn't say so explicitly, see 
http://docs.python.org/dev/py3k/library/stdtypes.html

"""
Iterating views while adding or deleting entries in the dictionary may raise 
a RuntimeError or fail to iterate over all entries.
"""

but I think you can change the values without converting the dictview to a 
list first:

>>> a = {1:2, 3:4, 5:6}
>>> for k, v in a.items():
...     a[k] = "+" * v
...
>>> a
{1: '++', 3: '++++', 5: '++++++'}




More information about the Tutor mailing list