Create
python
October 10, 20222 min read

Create SHA256 hash of a dict in python

As we've seen in earlier posts, you can create an SHA256 hash of a string and generate a hash in string type.

A python dict is a data structure that stores key-value pairs. The keys are used to access the values.

Example -

person = {'name' : 'Vamana', 'age': 20}

But, what if you had to create an sha256 hash of the person dictionary above? We can do it by first converting the dict to string format. Note that, a dictionary doesn't maintain the order of keys (key:values), so the value can change randomly when you try to use it as a complete dictionary. For this reason, we will sort the keys and then convert it to a string, to make sure that the order of keys is consistent always. We do this by passing sort_keys=True as the second parameter to json.dumps.

Here is an example with complete code of the above mentioned implementation.

import hashlib
import json

person = {'name' : 'Vamana', 'age': 20}
hash = hashlib.sha256(json.dumps(person, sort_keys=True).encode('utf-8')).hexdigest()
print(hash)

The output of the above code will return a SHA256 hash of the stringified version of the dict-

96eb8cf748554c982053204da0563d6176731e77d890a85b8a62cb39d6187259

I'm glad that you found this article to create SHA256 hash of a dict useful. Happy Coding.

Share this blog
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik
Satvik
Entrepreneur
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article
Next Article