Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass dictionary key as parameter to a function python

Tags:

python

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.

like image 243
Tester Avatar asked Jun 25 '26 09:06

Tester


1 Answers

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) 

like image 113
Gelineau Avatar answered Jun 27 '26 22:06

Gelineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!