Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can get rid of None values in dictionary?

Tags:

python

Something like:

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

This code raise exception because changing of dictionary when iterating.

I discover only non pretty solution with another dictionary:

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

Thanks

like image 788
Vojta Rylko Avatar asked Mar 30 '10 11:03

Vojta Rylko


People also ask

How do I remove an empty key from a dictionary?

In Python, the clear() method is used to delete a dictionary Python. This method removes all the keys values pairs that are available in the dictionary and always returns a none value or empty dictionary.

Can we delete values in dictionary Python?

The Python del statement deletes an object. Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary.

Can none be a dictionary value?

The dictionary keys and values can be of any type. They can also be None .


1 Answers

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} 
like image 89
John La Rooy Avatar answered Oct 07 '22 14:10

John La Rooy