gpt4 book ai didi

python - 使用点分隔字符串的动态字典值访问

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:21 25 4
gpt4 key购买 nike

我使用的是 Python 3.5.1

所以我想做的是在字典中传递一个点分隔的字符串,表示键和默认值的路径。我想检查键是否存在,如果不存在,请提供默认值。问题是我想要访问的 key 可能嵌套在其他字典中,直到运行时我才会知道。所以我想做的是这样的:

def replace_key(the_dict, dict_key, default_value):
if dict_key not in the_dict:
the_dict[dict_key] = default_value
return the_dict

some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}}
key_to_replace = 'top_property.first_nested.second_nested'
default_value = 'replaced'
#this would return as {'top_property': {'first_nested': {'second_nested': 'replaced'}}}
replace_key(some_dict, key_to_replace, default_value)

我正在寻找一种方法来做到这一点,而不必对“.”进行分割。在字符串中并迭代可能的键,因为这可能会变得困惑。我宁愿不必使用第三方库。我觉得有一种干净的 Pythonic 方式可以做到这一点,但我就是找不到它。我已经仔细研究了文档,但无济于事。如果有人对我如何做到这一点有任何建议,我将非常感激。谢谢!

最佳答案

您可以使用递归:

def replace_key(the_dict, dict_keys, default_value):
if dict_keys[0] in the_dict:
if len(dict_keys)==1:
the_dict[dict_keys[0]]=default_value
else:
replace_key(the_dict[dict_keys[0]], dict_keys[1:],default_value)
else:
raise Exception("wrong key")


some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}}
key_to_replace = 'top_property.first_nested.second_nested'
default_value = 'replaced'
#this would return as {'top_property': {'first_nested': {'second_nested': 'replaced'}}}
replace_key(some_dict, key_to_replace.split("."), default_value)

但它仍然使用 split()。但也许您认为它不那么困惑?

关于python - 使用点分隔字符串的动态字典值访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832563/

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