'Merge dicts with different key types

When trying to merge dictionaries with different key types:

a: dict[int, str] = {5: "hohoho"}
b: dict[str, str] = {"hi": "hello"}

c = a | b

Mypy version 0.812 complains with mypy_dict_merge.py:4: error: Unsupported operand types for | ("Dict[int, str]" and "Dict[str, str]")

I expected mypy to infer a type Dict[Union[int, str], str]. I found that I can do

c = cast(dict[Union[int, str], str], a) | cast(dict[Union[int, str], str], a)

But that feels a bit clumsy, and there is no check that the cast makes any sense. Is there a better way?

Edit: As users have pointed out that I should just use different types in the first place - this is a simplified example, let's assume a and b just store the results of functions, and I cannot modify those functions. So

a = function_that_returns_dicts_with_keys_of_type_Apple()
b = function_that_returns_dicts_with_keys_of_type_Orange()
c = a | b


Solution 1:[1]

It would be easier to instead declare the two dictionaries as the same type. By declaring the two dictionaries as different types, we are needlessly adding a complication to the problem.

If you need to use the integer key value, this can be cast later on. Try something like this:

a: dict[str, str] = {"5": "hohoho"}
b: dict[str, str] = {"hi": "hello"}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JensenMcKenzie