📅  最后修改于: 2023-12-03 14:45:57.449000             🧑  作者: Mango
Python dictionaries are a very useful data structure as they provide a way to store mappings between keys and values. One common operation when working with dictionaries is retrieving a value by its corresponding key.
The get()
method is a common way to retrieve a value by its key from a dictionary in Python. It takes one required argument, which is the key you want to retrieve the corresponding value for. If the key is found in the dictionary, the corresponding value is returned. If the key is not found, None
is returned by default.
Here's an example of how to use the get()
method:
my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict.get("banana")) # Output: 2
print(my_dict.get("grape")) # Output: None
In this example, my_dict
is a dictionary with three key-value pairs. We use the get()
method to retrieve the value for the key "banana"
, which returns 2
. We also try to retrieve the value for the key "grape"
, which is not found in the dictionary, so the method returns None
.
Optionally, you can provide a second argument to the get()
method, which is a default value to be returned if the key is not found in the dictionary. Here's an example:
my_dict = {"apple": 1, "banana": 2, "orange": 3}
print(my_dict.get("grape", "Not found")) # Output: Not found
In this example, we try to retrieve the value for the key "grape"
, which is not found in the dictionary. Since we provided a default value of "Not found"
, that value is returned instead of None
.
Overall, the get()
method is a useful way to retrieve values by their keys from dictionaries in Python.
####More about dictionaries
Dictionaries in Python are implemented using a hash table. This means that when you add a new key-value pair to a dictionary, Python calculates a hash value for the key, and uses that value to store the value at a specific location in memory. When you retrieve a value by its key, Python calculates the hash value for the key again, and uses that value to look up the corresponding value in memory.
Dictionaries are very efficient data structures for lookups, as the hash table implementation allows for constant-time lookups in most cases. However, they have some limitations - for example, they don't preserve the order of the key-value pairs, and they can't have duplicate keys. Overall, dictionaries are a versatile and commonly-used data structure in Python.