Chris Dutrow
Chris Dutrow

Reputation: 50362

Hash values with different data types together?

Question:

What is a good way to get a hash from a group of values of different data types (in Python)?

The values need to be hashed in a consistent order. Values that need to be hashed are strings and integers.

Example:

value1 = 'coconut'
value2 = 1.23

hash = Sha1Hash(value1, value2)

Could always concat into a string, but feel like this is less than ideal:

hash = Sha1Hash( '%s%s' % (value1, value2))

Upvotes: 2

Views: 649

Answers (2)

unutbu
unutbu

Reputation: 879729

It looks like you want a sha1 hash value. Python comes with a sha1 hash function, but it requires a string as input. Your data, (value1, value2), therefore needs to be serialized.

Since your data consists of only strings, ints and floats, you could serialize it and preserve the order of the values with

str([value1, value2])

import hashlib

value1 = 'coconut'
value2 = 1.23

m = hashlib.sha1()
m.update(str([value1, value2]))
print(m.hexdigest())            
# 1381ae81c8a5b660cca5b8d4607aa378320e25e8

Upvotes: 1

snapshoe
snapshoe

Reputation: 14264

Just make a tuple of the values, and hash that:

>>> Sha1Hash((value1, value2))

or use the standard hash function:

>>> hash((value1, value2))

Upvotes: 2

Related Questions