Getting the key of a Python dictionary by value
The python dictionary operation of getting values with the keys of a key-value pair is still relatively simple.
Example:
d = {1:'a', 2:'a', 3:'b', 5:'c'} print(d[5])
The output result is:
c
However, since values are not unique in the dictionary, looking up the key corresponding to a value is quite laborious. Here is a function that looks up the key from the value, resulting in a list of keys corresponding to the input value:
def get_keys_by_value(the_dict, the_value): rl = list() for k in the_dict.keys(): if the_dict[k] == the_value: (k) return rl if __name__ == "__main__": d = {1:'a', 2:'a', 3:'b', 8:'f'} print('the keys are: ', get_keys_by_value(d, 'a'))
The first parameter (the_dict) of the function get_keys_by_value is the dictionary object on which the function operates, the second parameter (the_value) is the value to be queried, and the return parameter is the corresponding key, and the type of the return value is a list since there may be more than one corresponding key.
The result of the run is:
======================== RESTART: C:/Users/luh/ ========================
the keys are: [1, 2]
>>>
We generally use this function when we need to find a key by value in programming.
Several ways to fetch values from python dictionaries
A Python dictionary (dictionary) is a mutable container model that can store any number of data of any type. Each element of a dictionary consists of a key and a value, separated by a colon. Dictionaries are typically used to store data in key-value pairs, such as records in a database.
Here are a few methods of Python dictionary fetching and their code demonstrations:
Method 1: Use square bracket [ ] operators
Use the square bracket [ ] operator to get the corresponding value in the dictionary by key.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Get the value of the "name" key in the dictionary. value = my_dict["name"] print(value) # exports:Tom
Method 2: Use the get() method
Use the get() method to get the corresponding value in the dictionary by key, or return None if the key does not exist.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Get the value of the "name" key in the dictionary. value = my_dict.get("name") print(value) # Output: Tom # Get the value of the key "phone" in the dictionary, returns None since "phone" does not exist. value = my_dict.get("phone") print(value) # exports:None
Method 3: Use the items() method
Use the items() method to get all the key-value pairs in the dictionary, returning a list containing all the key-value pairs, where each element in the list is a tuple, the first element of the tuple is the key, and the second element is the value.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Get all key-value pairs in the dictionary items = my_dict.items() print(items) # Output: dict_items([('name', 'Tom'), ('age', 18), ('gender', 'male')]) # Iterate over all key-value pairs for key, value in items: print(f"{key}: {value}")
Method 4: Use the keys() method
Use the keys() method to get all the keys in the dictionary, returning a list of all the keys.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Get all keys in the dictionary keys = my_dict.keys() print(keys) # Output: dict_keys(['name', 'age', 'gender']) # Iterate over all keys for key in keys: value = my_dict[key] print(f"{key}: {value}")
Method 5: Using the values() method
Use the values() method to get all the values in the dictionary, returning a list of all the values.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Get all values in the dictionary values = my_dict.values() print(values) # Output: dict_values(['tom', 18, 'male']) # Iterate over all values for value in values: print
Method 6: Use of the in keyword
Use the in keyword to determine whether a key is in the dictionary, returning True if it is and False otherwise.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Determine if "name" is in the dictionary # if "name" in my_dict: print("name is in my_dict") # Output: name is in my_dict # Determine if "phone" is in the dictionary. if "phone" in my_dict: print("phone is in my_dict") else: print("phone is not in my_dict") # exports:phone is not in my_dict
Method 7: Using the pop() method
Use the pop() method to remove the key-value pair for the specified key in the dictionary and return the corresponding value.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Delete the key-value pair for the "age" key in the dictionary and return the corresponding value value = my_dict.pop("age") print(value) # Output: 18 print(my_dict) # exports:{"name": "Tom", "gender": "male"}
Method 8: Using the popitem() method
Using the popitem() method you can delete any key-value pair in the dictionary and return the corresponding key-value pair, which is returned as a tuple where the first element of the tuple is the key and the second element is the value.
# Define a dictionary my_dict = {"name": "Tom", "age": 18, "gender": "male"} # Delete any key-value pair in the dictionary and return the corresponding key-value pair key, value = my_dict.popitem() print(key, value) # Output: gender male print(my_dict) # exports:{"name": "Tom", "age": 18}
This is a demonstration of several methods of Python dictionary fetching and their code.
ultimate
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.