0

I wanted to know if you could hash a dictionary? Currently playing around with Blockchain! Here's the code I would like to hash:

def add_transactions():

    transaction = {

      "previous_block_hash": previous_block_hash() ,

      "index": increase_index(),

      "item": item(),

      "timestamp": datetime.datetime.now(),

      "sender": get_sender(),

      "receiver": get_receiver()

    }

Wanted to know the best way to apply hashlib to get 256 value a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2

petezurich
  • 9,280
  • 9
  • 43
  • 57
Victor Nwadike
  • 97
  • 1
  • 10

2 Answers2

7

Dictionary is unhashable data type in python. So you cannot hash a dictionary object. But, if you need to have some check sum you can serialize dictionary and then calculate its hash (just a workaround that can help).

For example using jsonpickle and hashlib:

import jsonpickle
import hashlib

dct = {"key": "value"}

serialized_dct = jsonpickle.encode(dct)

check_sum = hashlib.sha256(serialized_dct.encode('utf-8')).digest()

print(check_sum)

UPD:

Glich's code example is not precise and needs to be improved in this way:

import json
import hashlib

s = json.dumps({'test dict!': 42}).encode('utf-8')

print(hashlib.md5(s).digest()) 
Artsiom Praneuski
  • 2,259
  • 16
  • 24
1

The hashlib functions require a buffer (they work on raw data, not abstract objects whose data layout is an implementation detail of your Python interpreter). This means you'll have to serialize your data in some way first.

For example, you could convert your dict to JSON first using the json module.

>>> import json
>>> import hashlib
>>> hashlib.md5(json.dumps({'test dict!':42}))
<md5 HASH object @ 0000000002831058>
>>> _.digest()
'bg\xa3\xa5y)\x1f\xef\x8eP\xcd\xef\xfb7B\xb8'
gilch
  • 10,813
  • 1
  • 23
  • 28
  • It doesn't work in python 3.10.5. Throws `TypeError: Strings must be encoded before hashing`. See @artsiom-praneuski answer for the fix. – felippeduran Jul 24 '23 at 16:56