I have a nested dictionary and i have a use case where i need to update a certain key in the nested dictionary by passing it into a function. See the below code for example:
sample_dict = {
'a':{'b':{'c':"Bye"},'f':{'d':"Tata"}},'g':{'e':"SeeYou"}
}
def value_modifier(key,new_value):
key = new_value
value_modifier(sample_dict['a']['b']['c'],new_value="Hi")
# here i know i am not passing the key but its value
print(sample_dict) # this prints the original sample_dict
# but i want my dict as below after my desired operation:
{
'a':{'b':{'c':"Hi"},'f':{'d':"Tata"}},'g':{'e':"SeeYou"}
}
I also looked for solution using memory address,etc as well but i am not able to update my sample_dict's desired key's value.
You may pass 2 arguments to your function:
sample_dict = {
'a':{'b':{'c':"Bye"},'f':{'d':"Tata"}},'g':{'e':"SeeYou"}
}
def value_modifier(parent, key, new_value):
parent[key] = new_value
value_modifier(sample_dict['a']['b'], 'c', new_value="Hi")
print(sample_dict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With