Use Dictionary Union
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: use-dictionary-union
Section titled “Sourcery refactoring id: use-dictionary-union”Description
Section titled “Description”Replace a sequence of unpacked dictionaries with a use of the dictionary union operator.
Before
Section titled “Before”tube_stops = { "Piccadilly": ["Heathrow", "King's Cross"], "Bakerloo": ["Baker Street", "Oxford Circus"],}bus_stops = { "65": ["Kingston Station", "Kew Bridge"],}all_stops = {**tube_stops, **bus_stops}tube_stops = { "Piccadilly": ["Heathrow", "King's Cross"], "Bakerloo": ["Baker Street", "Oxford Circus"],}bus_stops = { "65": ["Kingston Station", "Kew Bridge"],}all_stops = tube_stops | bus_stopsExplanation
Section titled “Explanation”The dictionary union operator was introduced in Python 3.9 (see PEP 584). It provides an interface for dictionaries similar to set unions, where the result combines the keys from both dictionaries, with the right dictionary taking precedence in the case of duplicates. This is clearer, more concise, and more discoverable than using dictionary unpacking to create a new dictionary.
See also: dict-assign-update-to-union