diff --git a/kheops/utils.py b/kheops/utils.py index a6e37d7..89ad75e 100644 --- a/kheops/utils.py +++ b/kheops/utils.py @@ -4,6 +4,10 @@ import collections import logging from pathlib import Path +import hashlib +import json +from typing import Dict, Any + from jinja2 import Template from jsonschema import Draft7Validator, validators from pprint import pprint @@ -73,6 +77,16 @@ class Default(dict): def __missing__(self, key): return "" +# Source: https://www.doc.ic.ac.uk/~nuric/coding/how-to-hash-a-dictionary-in-python.html +def dict_hash(dictionary: Dict[str, Any]) -> str: + """MD5 hash of a dictionary.""" + dhash = hashlib.md5() + # We need to sort arguments so {'a': 1, 'b': 2} is + # the same as {'b': 2, 'a': 1} + encoded = json.dumps(dictionary, sort_keys=True).encode() + dhash.update(encoded) + return dhash.hexdigest() + def render_template_python(text, params, ignore_missing=True): """Render template for a given string"""