Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to remove keys in dictionary with None values in Python

What is the proper way to remove keys from a dictionary with value == None in Python?

like image 420
Newboy11 Avatar asked Nov 19 '15 06:11

Newboy11


People also ask

Can you remove a key from a dictionary Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

What is the wrong way of deleting the value of key key from a dictionary in Python?

Remove a Key Using pop(key,d) So only use pop(key) if you're confident that the key exists in the dictionary. If you are unsure if the key exists then put a value for the second, optional argument for pop() - the default value. Instead of throwing a KeyError it will return that value.

How do you remove key marks from a dictionary?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.


2 Answers

Generally, you'll create a new dict constructed from filtering the old one. dictionary comprehensions are great for this sort of thing:

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

If you must update the original dict, you can do it like this ...

filtered = {k: v for k, v in original.items() if v is not None} original.clear() original.update(filtered) 

This is probably the most "clean" way to remove them in-place that I can think of (it isn't safe to modify a dict while you're iterating over it)


Use original.iteritems() on python2.x

like image 83
mgilson Avatar answered Oct 09 '22 11:10

mgilson


if you need to delete None values recursively, better to use this one:

def delete_none(_dict):     """Delete None values recursively from all of the dictionaries"""     for key, value in list(_dict.items()):         if isinstance(value, dict):             delete_none(value)         elif value is None:             del _dict[key]         elif isinstance(value, list):             for v_i in value:                 if isinstance(v_i, dict):                     delete_none(v_i)      return _dict 

with advice of @dave-cz, there was added functionality to support values in list type.

@mandragor added additional if statement to allow dictionaries which contain simple lists.

Here's also solution if you need to remove all of the None values from dictionaries, lists, tuple, sets:

def delete_none(_dict):     """Delete None values recursively from all of the dictionaries, tuples, lists, sets"""     if isinstance(_dict, dict):         for key, value in list(_dict.items()):             if isinstance(value, (list, dict, tuple, set)):                 _dict[key] = delete_none(value)             elif value is None or key is None:                 del _dict[key]      elif isinstance(_dict, (list, set, tuple)):         _dict = type(_dict)(delete_none(item) for item in _dict if item is not None)      return _dict   passed: a = {     "a": 12, "b": 34, "c": None,     "k": {"d": 34, "t": None, "m": [{"k": 23, "t": None},[None, 1, 2, 3],{1, 2, None}], None: 123} }  returned: a = {     "a": 12, "b": 34,      "k": {"d": 34, "m": [{"k": 23}, [1, 2, 3], {1, 2}]} } 
like image 21
Vova Avatar answered Oct 09 '22 09:10

Vova