[英]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)
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.