How do I hash dicts in Python across multiple processes?

Learn how to hash dictionaries in Python across multiple processes using the built-in libraries.

Python, hashing, dictionaries, multiprocessing, performance.


import hashlib
import multiprocessing
import json

def hash_dict(d):
    # Convert dict to JSON string and encode to bytes
    dict_string = json.dumps(d, sort_keys=True).encode('utf-8')
    # Create a SHA-256 hash of the dict
    return hashlib.sha256(dict_string).hexdigest()

if __name__ == '__main__':
    # Sample dictionaries to hash
    dicts_to_hash = [{'a': 1, 'b': 2}, {'b': 2, 'a': 1}, {'c': 3, 'a': 1}]

    # Create a pool of processes
    with multiprocessing.Pool(processes=4) as pool:
        hashed_results = pool.map(hash_dict, dicts_to_hash)

    print(hashed_results)
    

Python hashing dictionaries multiprocessing performance.