English 中文(简体)
Python中的Yaml合并
原标题:
  • 时间:2009-05-05 03:31:41
  •  标签:

所以我正在玩弄这个想法,为Python中的Pygame制作一个自己的(当然,任何人都可以使用)小模板库。我希望提供一个使用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与默认情况重叠的情况下,用户提供的分支将取代库提供的分支。

在任何情况下,如果用户提供的 YAML 与默认树没有重叠,则默认树会保持不变。

用户提供的 YAML 中提供的任何多余的树枝都将被添加。

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来解析文件,然后使用以下函数合并两个树:

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

Optionally, you could do a deep-copy of the user-tree before calling this function.





相关问题
热门标签