How I can get rid of None values in dictionary?

后端 未结 7 933
无人共我
无人共我 2020-12-03 02:26

Something like:

for (a,b) in kwargs.iteritems():
    if not b : del kwargs[a]

This code raise exception because changing of dictionary when

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 03:06

    I like the variation of your second method:

       res = dict((a, b) for (a, b) in kwargs.iteritems() if b is not None)
    

    it's Pythonic and I don't think that ugly. A variation of your first is:

       for (a, b) in list(kwargs.iteritems()):
           if b is None:
                del kwargs[a]
    

提交回复
热议问题