Home >Backend Development >Python Tutorial >Introduction to Python functions: usage and examples of hash functions
Introduction to Python functions: Usage and examples of hash function
For example, we can use the hash function to hash the string:
string = "Hello World" hash_value = hash(string) print(hash_value)
In the above code, we use the hash function to hash the string "Hello World" , and assign the result to the hash_value variable. Finally, we output the hash value via the print function.
3.1 Hash string
string = "Hello World" hash_value = hash(string) print(hash_value)
Output: 2922927337147303222
In this example, we have the string " Hello World" performs a hash operation and prints out the hash value.
3.2 Hash integer
num = 12345 hash_value = hash(num) print(hash_value)
Output: 12345
In this example, we hash the integer 12345 and print out the hash value. Since an integer is an immutable object, its hash value is equal to itself.
3.3 Hash tuple
tuple_1 = (1, 2, 3) hash_value_1 = hash(tuple_1) tuple_2 = (4, 5, 6) hash_value_2 = hash(tuple_2) print(hash_value_1) print(hash_value_2)
Output:
In this example, we hash two tuples separately and print out their hash values.
3.4 Hash Dictionary
dict_1 = {"name": "Alice", "age": 18} hash_value_1 = hash(frozenset(dict_1.items())) dict_2 = {"name": "Bob", "age": 20} hash_value_2 = hash(frozenset(dict_2.items())) print(hash_value_1) print(hash_value_2)
Output:
In this example, we hash the two dictionaries separately and print out their hash values. Since the dictionary is a mutable object, we need to convert it to an immutable frozenset object before performing a hash operation.
Summary
Through this article, we learned the usage and examples of hash function and understood its basic operation. In actual programming, reasonable use of hash functions can improve program performance and efficiency.
The above is the detailed content of Introduction to Python functions: usage and examples of hash functions. For more information, please follow other related articles on the PHP Chinese website!