Skip to content

Use Dictionary Union

Sourcery refactoring id: use-dictionary-union

Description

Replace a sequence of unpacked dictionaries with a use of the dictionary union operator.

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}

After

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

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

Back to top