简体   繁体   English

比较两个 YAML 文件中的键并打印差异?

[英]Compare keys in two YAML files and print differences?

If we have two yaml files how would we compare keys and print mismatched and/or missing keys?如果我们有两个 yaml 文件,我们将如何比较密钥并打印不匹配和/或丢失的密钥? I tried DeepDiff but it takes dictionaries, iterables, etc, how would I convert yaml files to dictionary and use DeepDiff or any other method?我尝试了 DeepDiff,但它需要字典、可迭代对象等,我如何将 yaml 文件转换为字典并使用 DeepDiff 或任何其他方法?

Following worked for me:以下为我工作:

import yaml
from deepdiff import DeepDiff

def yaml_as_dict(my_file):
    my_dict = {}
    with open(my_file, 'r') as fp:
        docs = yaml.safe_load_all(fp)
        for doc in docs:
            for key, value in doc.items():
                my_dict[key] = value
    return my_dict

if __name__ == '__main__':
    a = yaml_as_dict(yaml_file1)
    b = yaml_as_dict(yaml_file2)
    ddiff = DeepDiff(a, b, ignore_order=True)
    print(ddiff)

Try out this package deepdiff .I had a similar usecase and found it very helpfull.试试这个 package deepdiff 。我有一个类似的用例,发现它非常有帮助。

Use PyYAML To convert to flattened dict , then compare.使用PyYAML来转换为扁平化的dict ,然后进行比较。

To load a yaml file as a dictionary you can use PyYAML:要将 yaml 文件加载为字典,您可以使用 PyYAML:

import yaml

with open("example.yaml", 'r') as fp:
    d = yaml.safe_load(fp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM