gpt4 book ai didi

python - 将字典键作为参数传递给函数 python

转载 作者:行者123 更新时间:2023-12-03 07:52:08 25 4
gpt4 key购买 nike

我有一个嵌套字典,并且有一个用例,我需要通过将嵌套字典中的某个键传递给函数来更新它。请参阅下面的代码示例:

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"}
}

我还寻找使用内存地址等的解决方案,但我无法更新我的sample_dict所需的键值。

最佳答案

您可以向函数传递 2 个参数:

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)

关于python - 将字典键作为参数传递给函数 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76930538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com