Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? I tried DeepDiff but it takes dictionaries, iterables, etc, how would I convert yaml files to dictionary and use DeepDiff or any other method?

like image 508
Faisal Avatar asked Sep 05 '25 03:09

Faisal


1 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)
like image 169
Faisal Avatar answered Sep 07 '25 19:09

Faisal