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()
}
Run Code Online (Sandbox Code Playgroud)
Wanted to know the best way to apply hashlib to get 256 value
a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2
字典是python中不可散列的数据类型。所以你不能散列字典对象。但是,如果您需要一些校验和,您可以序列化字典,然后计算其哈希(只是一种可以提供帮助的解决方法)。
例如使用jsonpickle和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)
Run Code Online (Sandbox Code Playgroud)
更新:
Glich的代码示例不精确,需要这样改进:
import json
import hashlib
s = json.dumps({'test dict!': 42}).encode('utf-8')
print(hashlib.md5(s).digest())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4351 次 |
| 最近记录: |