简体   繁体   中英

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

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]

String replacement ? and converting a string into a dict with ast... ??

a={}
a[1] = { 2 : 4 }
a[2] = { 3 : { 3 : 4 }}

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


aStr = str(a)
for key,value in replacement.iteritems() :
    aStr = aStr.replace( str(key), "'%s'"%value )

import ast
newA = ast.literal_eval(aStr)
print newA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM