-2

Consider that you have a nested dictionary as the following:

{
    "text": "hi",
    "next": {
        "text": "hi",
        "next": {
            "text": "hi",
        }
    }
}

Now I want to change the last node to {"text": "bye"}, so that my end result is as follows:

{
    "text": "hi",
    "next": {
        "text": "hi",
        "next": {
            "text": "bye",
        }
    }
}

Remember that there can be thousands of nodes but I want to modify just the last node. How can I do it?

accdias
  • 5,160
  • 3
  • 19
  • 31
Saptak Bhoumik
  • 127
  • 3
  • 9

3 Answers3

1

Looping through dictionary, getting last object and changing it

d = {
"text":"hi",
"next":{
        "text":"hi",
        "next":{
                "text":"bye"
                  }
}
}

pre = d
while True:
    next_ = pre.get('next')
    if not next_:
        pre['text'] = 'bye'
        break
    pre = next_
print(d)
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
1

if you know the depth of the dictionary, you can use reduce as explained here:

from functools import reduce
def reduce_dict(data, items):
    return reduce(dict.get, items, data)
depth = 1000
reduce_dict(my_dict, ['next']* depth)['text'] = 'bye'
Mohammad
  • 3,276
  • 2
  • 19
  • 35
  • If we have the depth, we might also have the tail and just do `tail['text'] = 'bye'` :-) – Kelly Bundy Aug 22 '21 at 15:23
  • Depending on how you are collecting the information, it is not uncommon to be provided with the constraints of the input (here the depth) to properly process the data. Having `tail`, while convenient is not that common. – Mohammad Aug 22 '21 at 15:27
1
root = {'text': 'hi', 'next': {'text': 'hi', 'next': {'text': 'hi'}}}

node = root
while 'next' in node:
    node = node['next']
node['text'] = 'bye'

print(root)

Output:

{'text': 'hi', 'next': {'text': 'hi', 'next': {'text': 'bye'}}}
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65