Add: function to hash dict

This commit is contained in:
mrjk 2022-05-04 18:41:53 -04:00
parent 1dce6fbfcd
commit c0621eb01c

View File

@ -4,6 +4,10 @@ import collections
import logging import logging
from pathlib import Path from pathlib import Path
import hashlib
import json
from typing import Dict, Any
from jinja2 import Template from jinja2 import Template
from jsonschema import Draft7Validator, validators from jsonschema import Draft7Validator, validators
from pprint import pprint from pprint import pprint
@ -73,6 +77,16 @@ class Default(dict):
def __missing__(self, key): def __missing__(self, key):
return "" 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): def render_template_python(text, params, ignore_missing=True):
"""Render template for a given string""" """Render template for a given string"""