Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Remove item from dictionary in functional way

I've been programming in Python for quite a while now. I've always wondered, is there a way to remove an item from a dictionary and return the newly created dictionary? Basically removing an item from a dict in a functional way.

As far as I know, there are only the del dict[item] and dict.pop(item) methods, however both modify data and don't return the new dict.

like image 495
Omniscient Potato Avatar asked Aug 05 '26 12:08

Omniscient Potato


1 Answers

There is no built-in way for dicts, you have to do it yourself. Something to the effect of:

>>> data = dict(a=1,b=2,c=3)
>>> data
{'a': 1, 'b': 2, 'c': 3}
>>> {k:v for k,v in data.items() if k != item}

Note, Python 3.9 did add a | operator for dicts to create a new, merged dict:

>>> data
{'a': 1, 'b': 2, 'c': 3}
>>> more_data = {"b":4, "c":5, "d":6}

Then

>>> data | more_data
{'a': 1, 'b': 4, 'c': 5, 'd': 6}

So, similar to + for list concatenation. Previously, could have done something like:

>>> {**data, **more_data}
{'a': 1, 'b': 4, 'c': 5, 'd': 6}

Note, set objects support operators to create new sets, providing operators for various basic set operations:

>>> s1 = {'a','b','c'}
>>> s2 = {'b','c','d'}
>>> s1 & s2 # set intersection
{'b', 'c'}
>>> s1 | s2 # set union
{'c', 'a', 'b', 'd'}
>>> s1 - s2 # set difference
{'a'}
>>> s1 ^ s2 # symmetric difference
{'a', 'd'}

This comes down to API design choices.

like image 166
juanpa.arrivillaga Avatar answered Aug 08 '26 00:08

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!