Replacing all keys and values ​​in the nested python dictionary with new values

advertisements

Suppose I have a nested dict in python like:

a[1][2] = 4
a[1][3][3] = 5

And I have another straightforward non-nested dict like so:

{
    1 : "Kansas City",
    2 : "Toledo",
    3 : "Houston",
    4 : "Champaign",
    5 : "Seattle"
}

How do I replace all the keys and values in the first dict that match the keys in the second dict with the second dict's corresponding values so that the output looks like:

a["Kansas City"]["Toledo"] = "Champaign"
a["Kansas City"]["Houston"]["Houston"] = "Seattle


I have taken a recursive approach which if the value of the data is dictionary - try to replace the keys and values. Else it treats the data as a single value and try to convert it.

replace_dict is the dictionary which points out how to convert values and data are the current values.

def replace_key_val(data, replace_dict):
    if type(data)== dict:
        return {replace_dict[k] : replace_key_val(v, replace_dict) for k,v in data.iteritems()}
    return replace_dict[data]