Is there a more readable way to convert types in a nested dictionary?

I have two dictionaries one with the values as strings and one with the types I want to convert to.

values = {
    "foreground": {
        "enabled": "True",
        "size": "720",
    "background": {
        "type": "Solid",
        "blur": "True",
        "blur_strength": "15.0",

types = {
    "foreground": {
        "enabled": bool,
        "size": int,
    "background": {
        "type": str,
        "blur": bool,
        "blur_strength": float,

We can assume that the string in values will convert to the corresponding type without raising an exception

Here is my current solution:

def correct_types(types: dict, values: dict) -> dict:
    output = {}
    for section, section_dict in values.items():
        output[section] = {}
        for setting, value in section_dict.items():
            output[section][setting] = types[section][setting](value)

    return output

It works fine but I feel there is probably a better way to do this that is easier to follow.


Your code is already in good shape.

Not sure about readability but I always find list comprehensions (dict comprehension in this case) to be a compact way of writing any such logic.

Try this –

{i:{k:types[i][k](v) for k,v in values[i].items()} for i in types.keys()}

##### OR #####

{i:{k:types.get(i).get(k)(v) for k,v in values.get(i).items()} for i in types.keys()}
{'foreground': {'enabled': True, 'size': 720},
 'background': {'type': 'Solid', 'blur': True, 'blur_strength': 15.0}}

The types[i][k]() OR types.get(i).get(k)() is the type class convertor such as int() or bool() where, i is for defining the first level of keys, and k is for the second level of keys.