Search code examples
pythonchecksum

Python, checksum of a dict


I'm thinking to create a checksum of a dict to know if it was modified or not For the moment i have that:

>>> import hashlib
>>> import pickle
>>> d = {'k': 'v', 'k2': 'v2'}
>>> z = pickle.dumps(d)
>>> hashlib.md5(z).hexdigest()
'8521955ed8c63c554744058c9888dc30'

Perhaps a better solution exists?

Note: I want to create an unique id of a dict to create a good Etag.

EDIT: I can have abstract data in the dict.


Solution

  • Something like this:

    reduce(lambda x,y : x^y, [hash(item) for item in d.items()])
    

    Take the hash of each (key, value) tuple in the dict and XOR them alltogether.

    @katrielalex If the dict contains unhashable items you could do this:

    hash(str(d))
    

    or maybe even better

    hash(repr(d))