[BangPypers] Python dictionaries, deleting elements while iterating.
Anand Chitipothu
anandology at gmail.com
Mon Feb 25 17:45:11 CET 2013
On Mon, Feb 25, 2013 at 9:50 PM, ragsagar <ragsagar at gmail.com> wrote:
> On Mon, Feb 25, 2013 at 9:33 PM, Anand Chitipothu <anandology at gmail.com
> >wrote:
>
> >
> > You can iterate over items:
> >
> > for key, value in dictionary.items():
> > if value == 1:
> > del dictionary[key]
> >
>
> I think in Python 3.*, dict.items() returns iterator. If so it won't work
> in Python 3.* . So converting it to list would be a better option.
>
> for key in list(dictionary):
> if dictionary[key] == 1:
> del dictionary[key]
>
I think, the second solution I suggested is more Pythonic than using a for
loop. In Python 3, it can be written as a dictionary-comprehension.
dictionary = {(k, v) for k, v in dictionary.items() if v != 1}
Anand
More information about the BangPypers
mailing list