From c0621eb01cb6f957464c15e99de19269a3acd8e5 Mon Sep 17 00:00:00 2001 From: mrjk Date: Wed, 4 May 2022 18:41:53 -0400 Subject: [PATCH] Add: function to hash dict --- kheops/utils.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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"""