gpt4 book ai didi

python - 以最Pythonic的方式从字典列表生成配置样式文件

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

我有一个字典列表,

[{'section_id': 1, 
'parent_sec_id': 0,
'sec_name': 'apple',
'key1': 'val1'},
{'section_id': 2,
'parent_sec_id': 0,
'sec_name': 'banana',
'key2': 'val2'},
{'section_id': 3,
'parent_sec_id': 1,
'sec_name': 'orange',
'key3': 'val3'},
{'section_id': 4,
'parent_sec_id': 2,
'sec_name': 'guava',
'key4': 'val4'},
{'section_id': 5,
'parent_sec_id': 3,
'sec_name': 'grape',
'key5': 'val5'}]

每个字典都有一个字典标识符“section_id”,还有一个键“parent_section_id”,它告诉它是否是任何其他字典的子字典。所以基本上,如果parent_section_id设置为0(零),那么它是一个父字典,否则它是该部分id提到的字典的子字典。
现在,从上面的字典列表中,我被要求实现以下格式(是的,我被问到了,面试的一部分):

apple
{
'key1': 'val1'

orange
{
'key3': 'val3'

grape
{
'key5': 'val5'
}
}

}

banana
{
'key2': 'val2'

guava
{
'key4': 'val4'
}
}

有人告诉我这是用于为任何程序编写配置文件的格式。我只是好奇从这个字典列表生成文件的最佳方法是什么。

最佳答案

您可以递归输出 parent_sec_id 与给定父级 ID 匹配的节,并且子级的输出缩进:

def transform(sections, parent=0):
output = []
indent = ' ' * 4
for section in sections:
if section['parent_sec_id'] == parent:
output.extend((section['sec_name'], '{'))
for key, value in section.items():
if key not in ('section_id', 'parent_sec_id', 'sec_name'):
output.append("%s'%s': '%s'" % (indent, key, value))
output.extend(indent + line for line in transform(sections, section['section_id']))
output.append('}')
return output

假设您的字典示例列表存储为变量 sections,则 '\n'.join(transform(sections)) 将返回:

apple
{
'key1': 'val1'
orange
{
'key3': 'val3'
grape
{
'key5': 'val5'
}
}
}
banana
{
'key2': 'val2'
guava
{
'key4': 'val4'
}
}

关于python - 以最Pythonic的方式从字典列表生成配置样式文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940535/

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