Navid777 Navid777 - 16 days ago 13
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
bencode
returns this error:

KeyError: <type 'unicode'>

Answer

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