Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 已知的字典结构,但非常嵌套-替代丑陋的代码_Python_Dictionary_Plist - Fatal编程技术网

Python 已知的字典结构,但非常嵌套-替代丑陋的代码

Python 已知的字典结构,但非常嵌套-替代丑陋的代码,python,dictionary,plist,Python,Dictionary,Plist,使用plistlib在Python中加载plist文件,我有一个数据结构可以使用,其中指向键值对的给定路径应该永远不会失败,因此我可以接受在没有.get()和其他技巧的情况下硬编码路径——然而,这是一条又长又难看的路径。plist中充满了dict数组中的dict,因此它最终看起来是这样的: def input_user_data(plist, user_text): new_text = clean_user_data(user_data) plist['template_dat

使用
plistlib
在Python中加载plist文件,我有一个数据结构可以使用,其中指向键值对的给定路径应该永远不会失败,因此我可以接受在没有
.get()
和其他技巧的情况下硬编码路径——然而,这是一条又长又难看的路径。plist中充满了dict数组中的dict,因此它最终看起来是这样的:

def input_user_data(plist, user_text):
    new_text = clean_user_data(user_data)
    plist['template_data_array'][0]['template_section']['section_fields_data'][0]['disclaimer_text'] = new_text  #do not like
#....
one = plist['template_data_array']
two = one[0]['template_section']['section_fields_data']
two[0]['disclaimer_text'] = new_text
除了超过了79个字符的限制外,它看起来只是悲伤和二年级。然而,像这样一步一步走过它似乎同样愚蠢:

def input_user_data(plist, user_text):
    new_text = clean_user_data(user_data)
    plist['template_data_array'][0]['template_section']['section_fields_data'][0]['disclaimer_text'] = new_text  #do not like
#....
one = plist['template_data_array']
two = one[0]['template_section']['section_fields_data']
two[0]['disclaimer_text'] = new_text
…因为我并不真的需要所有这些任务,我只是想清理用户文本并将其放入plist的预定义部分


当处理一个嵌套路径时,它总是存在的,但是访问起来很乏味(并且可能确实需要通过其他方法再次找到),是有一种更短的技术可以使用,还是我只是咧嘴笑着忍受我无法控制的糟糕的嵌套结构?

当你看到大量重复的或样板代码时,这通常暗示您可以将重复操作重构为函数。编写
get_node
set_node
helper函数不仅使设置值的代码更简单,还允许您轻松地将路径定义为常量,您可以将所有路径放在代码中的一个位置以便于维护

def get_node(container, path):
    for node in path:
        container = container[node]
    return container

def set_node(container, path, value):
    container = get_node(container, path[:-1])
    container[path[-1]] = value

DISCLAIMER_PATH = ("template_data_array", 0, "template_section", "section_fields_data", 
                   0, "disclaimer_text")

set_node(plist, DISCLAIMER_PATH, new_text)

潜在地,您可以将
plist
的类划分为子类,将它们作为方法,甚至覆盖
\uuuu getitem\uuuuu
\uuu setitem\uuuuuu
,这会很方便。

不确定为什么
get\u node
对我来说不是自然发生的,这真的很巧妙+1.