How I can get rid of None values in dictionary?

后端 未结 7 943
无人共我
无人共我 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:22

    Another way to write it is

    res = dict((k,v) for k,v in kwargs.iteritems() if v is not None)
    

    In Python3, this becomes

    res = {k:v for k,v in kwargs.items() if v is not None}
    

提交回复
热议问题