TIL: Union Operator

Today I discovered the dictionaries union operator |.

>>> dict1 = {"a": "a", "b": "b"}
>>> dict2 = dict1 | {"c": "c"}
>>> dict2
{'a': 'a', 'b': 'b', 'c': 'c'}

I found it to be very useful for testing APIs, where I create base payload with data that’s common for all payloads and then I create a specific payload for each request:

base_payload = {"my base": "field"}
client.post("/my/url", json = base_payload | {"my custom": "field"})
client.post("my/second/url", json = base_payload | {"other custom": "field"})

Mia Bajić's Picture

About Mia Bajić

I’m a Prague-based software engineer passionate about knowledge sharing & community building. I’m the main organizer of Prague Python Pizza & Prague Python meetups, and a co-organizer of EuroPython & PyCon CZ.