python - 以大多数pythonic方式从字典列表生成配置样式文件
问题描述
我有一个字典列表,
[{'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'
}
}
有人告诉我这是用于为任何程序编写配置文件的格式。我只是好奇从这个字典列表中生成文件的最佳方法是什么。
解决方案
不是很优雅,但是您可以在 a 中收集您的项目collections.defaultdict()
,然后将您的字典路径输出到一个新文件。
基本思想是首先收集值为 0 的根父 ID,然后将后续子字典添加到这些根。您可以将每个列表中的最后一个值用作最近添加项目的父 ID。
演示:
from collections import defaultdict
def group_sections(data, parent_id, section_id, root_id = 0):
"""Groups sections into dictionary of lists, connecting on parent keys"""
groups = defaultdict(list)
# Separate root and rest of children
roots = [dic for dic in data if dic[parent_id] == root_id]
children = [dic for dic in data if dic[parent_id] != root_id]
# Add roots first
for root in roots:
groups[root[section_id]].append(root)
# Append children next
for child in children:
for key, collection in list(groups.items()):
# Get most recently added child
recent = collection[-1]
# Only add child if equal to parent
if child[parent_id] == recent[section_id]:
groups[key].append(child)
# Filter out result dictionary to not include parent and section ids
return {
k1: [
{k2: v2 for k2, v2 in d.items() if k2 != parent_id and k2 != section_id}
for d in v2
]
for k1, v2 in groups.items()
}
def write_config_file(filename, data, name_key):
"""Write config file, using dictionary of lists"""
# Writes n tabs to string
tab_str = lambda n: "\t" * n
with open(filename, mode="w") as config_file:
for group in data.values():
tabs = 0
for dic in group:
for key in dic:
# Write name key
if key == name_key:
config_file.write(
"%s%s\n%s{\n" % (tab_str(tabs), dic[key], tab_str(tabs))
)
tabs += 1
# Otherwise write key-value pairs
else:
config_file.write(
"%s'%s': '%s'\n" % (tab_str(tabs), key, dic[key])
)
# Write ending curly braces
for i in range(tabs - 1, -1, -1):
config_file.write("%s}\n" % (tab_str(i)))
if __name__ == "__main__":
list_dicts = [
{"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"},
]
data = group_sections(data=list_dicts, parent_id="parent_sec_id", section_id="section_id")
write_config_file(filename='config', data=data, name_key='sec_name')
配置文件:
apple
{
'key1': 'val1'
orange
{
'key3': 'val3'
grape
{
'key5': 'val5'
}
}
}
banana
{
'key2': 'val2'
guava
{
'key4': 'val4'
}
}
注意:这是一种迭代解决方案,而不是递归解决方案。
推荐阅读
- select - 使用 CQL 的 where 子句进行选择
- javascript - react-testing-library 为什么 toBeInTheDocument() 不是函数
- c++11 - 类内的朋友函数定义
- node.js - 在生产模式下在 React App 上从节点后端渲染图像
- node.js - 无法获取控制台标记以记录到自定义输出文件
- c++ - Buggy expression with pre-increment operator from order of evaluation or temporary object?
- php - 使用中间件时获取重定向循环
- react-native - 试图在本机反应中获取firebase图像存储url
- c# - 模型绑定忽略具有 JsonIgnore 属性的属性
- python - How to build a Python function to build Pandas DataFrames dynamically?