问题描述
所以我正在玩弄让自己(当然还有任何关心使用它的人)在 Python 中为 Pygame 制作一个小样板库的想法.我想要一个系统,其中应用程序的设置随 yaml 文件一起提供.
So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file.
所以我想如果库提供一个默认的 yaml 树并将它与用户提供的树合并它会很有用.出于可用性考虑,我想知道是否有任何人可以预测一个例程:
So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where:
在树中用户提供的 yaml 与默认值重叠的任何情况下,用户提供的分支都会替换库提供的分支.
In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones.
在用户提供的 yaml 不与默认树重叠的任何情况下,默认树仍然存在.
In any case where the user supplied yaml does not overlap the default tree, the default tree persists.
用户提供的 yaml 提供的树中的任何多余分支都会被附加.
Any superflous branches in the tree provided by the user supplied yaml are appended.
我知道这个解释很冗长,因为我的要求可能很清楚.我想知道免费获得是不是有点多.
I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.
推荐答案
你可以使用 PyYAML 来解析文件,然后使用以下函数合并两棵树:
You could use PyYAML for parsing the files, and then the following function to merge two trees:
def merge(user, default):
if isinstance(user,dict) and isinstance(default,dict):
for k,v in default.iteritems():
if k not in user:
user[k] = v
else:
user[k] = merge(user[k],v)
return user
或者,您可以在调用之前对用户树进行 deep-copy这个函数.
Optionally, you could do a deep-copy of the user-tree before calling this function.
这篇关于Python中的Yaml合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)