Computing an md5 hash of a data structure

后端 未结 7 1759
南旧
南旧 2020-12-04 10:13

I want to compute an md5 hash not of a string, but of an entire data structure. I understand the mechanics of a way to do this (dispatch on the type of the value, canonical

7条回答
  •  抹茶落季
    2020-12-04 10:58

    json.dumps() can sort dictionaries by key. So you don't need other dependencies:

    import hashlib
    import json
    
    data = ['only', 'lists', [1,2,3], 'dictionaries', {'a':0,'b':1}, 'numbers', 47, 'strings']
    data_md5 = hashlib.md5(json.dumps(data, sort_keys=True)).hexdigest()
    
    print(data_md5)
    

    Prints:

    87e83d90fc0d03f2c05631e2cd68ea02
    

提交回复
热议问题