Compare keys in two YAML files and print differences?

Viewed 7784

If we have two yaml files how would we compare keys and print mismatched and/or missing keys? I tried DeepDiff but it takes dictionaries, iterables, etc, how would I convert yaml files to dictionary and use DeepDiff or any other method?

4 Answers

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.

Use PyYAML To convert to flattened dict, then compare.

To load a yaml file as a dictionary you can use PyYAML:

import yaml

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