1

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
timgeb
  • 76,762
  • 20
  • 123
  • 145
user45183
  • 529
  • 1
  • 7
  • 16
  • 2
    You will have to use recursion and [Change the key value in python dictionary](http://stackoverflow.com/questions/4406501/change-the-key-value-in-python-dictionary). – Delgan Dec 08 '15 at 12:58
  • this would have been a little easier to answer if you had provided a full set of expected input and output. – timgeb Dec 08 '15 at 14:20

2 Answers2

1

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]
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
-1

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
cyrilc
  • 43
  • 4