removing items from a dictionary ?

Ben Finney bignose+hates-spam at
Fri Jul 27 02:05:26 CEST 2007

Stef Mientki <S.Mientki-nospam at> writes:

> I want to remove some items from a dictionary,
> so I would expect this should work:
>   Nets = {}
>   ... fill the dictionary Nets
>   for net in Nets:
>     if net.upper() in Eagle_Power_Nets :
>       del Nets [ net ]

Don't change the thing you're currently iterating over. Instead,
iterate over a copy:

    >>> eagle_power_nets = ['eggs', 'beans']
    >>> nets = {'spam': 10, 'eggs': 20, 'ham': 30}
    >>> for name in list(nets.keys()):
    ...     if name in eagle_power_nets:
    ...         del nets[name]
    >>> nets
    {'ham': 30, 'spam': 10}

Style hints (from <URL:>):

* Don't name an instance with Upper_Case; the convention is for
  instances to be named as lower_case_with_underscores, and classes to
  be named in TitleCase.

* Don't put spaces inside the bracketing characters '[]', '{}', '()'.

* Don't separate the item specifier '[foo]' or the function parameters
  '(bar)' from the identifier; instead follow it immediately,
  'foo_list[foo]', 'bar_func(bar)'.

None of these are mandatory, but they'll make your code comply with
what Python programmers expect and thus be more easily maintained.

 \           "Are you pondering what I'm pondering?" "Umm, I think so, |
  `\        Brain, but what if the chicken won't wear the nylons?"  -- |
_o__)                                            _Pinky and The Brain_ |
Ben Finney

More information about the Python-list mailing list