Q:

Conditionally merge dictionaries using ternary operators

I have a function that build a header according to the type of data it receives. I know I could make it with ifs, this is just a curiosity on how ternary operators can be embedded for some sort of dictionary comprehension.
I tried implementing the ternary just inside the dictionary and have it always output a dictionary.
def _create_header(self, data):
    base_header = {
        'type': data["type"],   # arg provided
        'dest_ID' : 1,          # arg provided
        'src_ ID': 2,           # arg provided
    }
    dest_header = {
        'dst_addr': 0,          # arg provided
    }
    data_header = {
        'priority': 0,          # arg provided
        'length': 0,            # arg provided
        'data_format': 0,       # arg provided
        'data_type': 0,         # arg provided
    }
    index_header = {
        'x_of_y': 0,            # len dependant
        'y': 0,                 # len dependant
    }
    protocol_header = {
        'check_type': 0,        # sys dependant
        'rev': 0,               # sys dependant
        'reserved': 0,          # rev dependant
    }
    header = {}
    return {**base_header, **dest_header if data["type"] in range(4,9) else {}, **data_header, **index_header, **protocol_header}

I always get Invalid Syntax, so I guess it might not be possible. Just wanted to know if anyone has tried it.

A:

The unary operator ** binds stronger than you think.
Paranthesize the ternary expression and it should work:
return {
    **base_header,
    **(dest_header if data["type"] in range(4,9) else {}),
    **data_header,
    **index_header,
    **protocol_header,
}

