[Tutor] Remove a dictionary entry

Peter Otten __peter__ at web.de
Sat Sep 18 11:13:13 CEST 2010


M. 427 wrote:

> (I am very new to python)
> I built a dictionary d={} of lists similar to this :
> 
> d = {
> 'a': ['apricot', 'apple'],
> 'b': ['beach', 'bear', 'bottle'],
> 'c': ['cold', 'cook', 'coleslaw'],
> 'd': ['deep'],
> 'e': ['expression', 'elephant']
> }
> 
> Now i want to go through this dictionary and remove all rows containing
> only one entry. How should I do that?

You should never iterate over a list or dictionary and add or remove items 
to it at the same time. That is a recipe for disaster even if it doesn't 
fail explicitly.

Instead create a new dictionary that contains only the items you are 
interested in:

>>> d = {
... 'a': ['apricot', 'apple'],
... 'b': ['beach', 'bear', 'bottle'],
... 'c': ['cold', 'cook', 'coleslaw'],
... 'd': ['deep'],
... 'e': ['expression', 'elephant']
... }
>>> result = {}
>>> for k, v in d.iteritems():
...     if len(v) > 1:
...             result[k] = v
...
>>> import pprint
>>> pprint.pprint(result)
{'a': ['apricot', 'apple'],
 'b': ['beach', 'bear', 'bottle'],
 'c': ['cold', 'cook', 'coleslaw'],
 'e': ['expression', 'elephant']}

Peter

PS: Instead of using the pretty print module "pprint" I could have typed

>>> result
{'a': ['apricot', 'apple'], 'c': ['cold', 'cook', 'coleslaw'], 'b': 
['beach', 'bear', 'bottle'], 'e': ['expression', 'elephant']}

The only difference is that it looks messier.




More information about the Tutor mailing list