Navid777 Navid777 - 6 months ago 52
Python Question

How to calculate MD5 checksum for a unicode dictionary?

I have a dictionary in python that contains unicode values in it. I want to calculate the md5 sum of this dictionary. I tried to use the answer to this question:Computing an md5 hash of a data structure

import hashlib
import bencode
data = {'unicode_text': 'سلام'}
data_md5 = hashlib.md5(bencode.bencode(data)).hexdigest()
print data_md5

But the problem is that
returns this error:

KeyError: <type 'unicode'>


The bencode library seems not to support unicode objects (anyway, it's written for Python 2, and I'm guessing you're using Python 3). How about using the built-in json module?

import hashlib
import json
data = {'unicode_text': 'سلام'}
data_md5 = hashlib.md5(json.dumps(data, sort_keys=True)).hexdigest()
print data_md5