Yaml在Python中合并 [英] Yaml merge in Python

查看:1200
本文介绍了Yaml在Python中合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想要使自己(和任何人谁在乎使用它当然)一个小的样板库在pygame的Python。我想要一个系统,其中应用程序的设置提供了一个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树并将其与用户提供的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

这篇关于Yaml在Python中合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆