How To Create a Unique Key For A Dictionary In Python

No - you can't rely on particular order of elements when converting dictionary to a string.

You can, however, convert it to sorted list of (key,value) tuples, convert it to a string and compute a hash like this:

a_sorted_list = [(key, a[key]) for key in sorted(a.keys())]
print hashlib.sha1( str(a_sorted_list) ).hexdigest()

It's not fool-proof, as a formating of a list converted to a string or formatting of a tuple can change in some future major python version, sort order depends on locale etc. but I think it can be good enough.


I prefer serializing the dict as JSON and hashing that:

import hashlib
import json

a={'name':'Danish', 'age':107}
b={'age':107, 'name':'Danish'}

# Python 2
print hashlib.sha1(json.dumps(a, sort_keys=True)).hexdigest()
print hashlib.sha1(json.dumps(b, sort_keys=True)).hexdigest()

# Python 3
print(hashlib.sha1(json.dumps(a, sort_keys=True).encode()).hexdigest())
print(hashlib.sha1(json.dumps(b, sort_keys=True).encode()).hexdigest())

Returns:

71083588011445f0e65e11c80524640668d3797d
71083588011445f0e65e11c80524640668d3797d