As a Python developer, I often come across situations where I need to ensure the integrity and security of data structures, such as dictionaries. In such cases, creating a hash of the dictionary can be incredibly useful. Today, I’m excited to share with you the process of creating a SHA-256 hash of a dictionary in Python. With this technique in your arsenal, you’ll be able to verify the integrity of data structures and detect any modifications or tampering. So, let’s dive into the world of hashing and Python!
As we’ve seen in earlier posts, you can create an SHA256 hash of a string and generate a hash in string type.
Creating a SHA256 hash of a dictionary in Python
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 SHA-256 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. We’ve reached the end of our journey into creating a SHA-256 hash of a dictionary in Python. I hope this exploration has shed light on the power and versatility of hashing techniques in maintaining data integrity. With the ability to create secure and tamper-proof hashes, you can ensure the accuracy and trustworthiness of your data structures. As you continue to dive deeper into the realm of Python development, remember the significance of data security and the role that hashing plays in maintaining it. Keep coding, keep hashing, and keep your data safe! Happy Coding.