Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
URL Rewriter Bot
URL Rewriter Bot

No - you can't rely on particular order of elements when converting dictionary to a stringyou 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.

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.

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.

Source Link
Tometzky
  • 24.2k
  • 5
  • 64
  • 79

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.