-1

So I have a list which acts as a 'map' of sorts, and a dict which is pulled from a JSON file.

For this example, lets say they look like this:

L = ['One', 'Two', 'Three']

D = {
    "One": {
        "Two": {
            "Three": {
                "Four": "String"
            }
        }
    }
}

I need a function for my game.

I will be passing it two things: L and a Object.

Note that L just leads to "Three" so thats what I want to replace. Though, I could be replacing "Four" or any other element at an unknown debth.

What I'm replacing could be a string, list, or dict, and I could be replacing it with any other object, including None, or a bool.

The structure of D needs to remain intact, besides the value being replaced.

Kieee
  • 126
  • 2
  • 15

2 Answers2

0

This function will take a list of strings as a path and an object to replace the located value with, operating on a global variable nested_dicts. If you want to adhere to a functional paradigm, you might want to rewrite it accordingly.

def replace (path, replacement):
    pointer = nested_dicts
    try:
        for key in path[:-1]:
            pointer = pointer[key]
    except KeyError:
        return False
    pointer[path[-1]] = replacement
    return True
黄雨伞
  • 1,904
  • 1
  • 16
  • 17
  • The result is just final value from path and it's new value, the rest of `D` needs to remain intact. – Kieee Apr 19 '17 at 15:24
  • 1
    I don't understand your statement "The result is just final value from path and it's new value". Is that what you think my code does, or what you want it to do? What it does is replace the specified value and leave the rest intact. – 黄雨伞 Apr 19 '17 at 15:30
  • 1
    Sorry, I was checking the result of `pointer`, I didn't know it replaced the original. – Kieee Apr 19 '17 at 15:46
0

Something like this works (path is L, o is the replacement):

L = ['One', 'Two', 'Three']

D = {
    "One": {
        "Two": {
            "Three": {
                "Four": "String"
            }
        }
    }
}

def replace(path, o):
    cur = D
    for k in path[:-1]:
        cur = cur[k]
    cur[path[-1]] = o

replace(L, {'msg': 'good'})
print(D)
lang2
  • 11,433
  • 18
  • 83
  • 133