How to extract the key from the dictionary according to the value in Python?

1 Introduction

When Python uses a dictionary to process related data, if we have a key value, it is easy to obtain the value corresponding to the key value of the dictionary, which is as simple as unlocking a lock with a key. But on the contrary, it is not so direct to obtain the corresponding key value according to the value.

In actual work, especially when the key and value have a one-to-one relationship, it becomes very important to extract the key based on the value. This is because the key and value are unique at this time, and both can be used as an index for searching.

Next, let us explore the function of how to extract the key from the dictionary according to the value.

2. Take a chestnut

First, we'll create a dictionary for sample illustration.
As shown below, currency_dict is a dictionary with currency abbreviations as keys and currency names as values.

currency_dict={
    
    'USD':'Dollar',
               'EUR':'Euro',
              ' GBP':'Pound',
               'CNY':'Chinese'}

If we have a key, just add the key in square brackets to get the corresponding value.
For example, using currency_dict['CNY']will return Chinese.

3. Use the list List

Using List to realize the above functions requires the following three steps:

  • Convert the key and value of the dictionary into lists key_list, value_list respectively
  • Find the subscript index corresponding to value from the list value_list
  • Use the above index to get the corresponding key from key_list

code show as below:

key_list=list(currency_dict.keys())
val_list=list(currency_dict.values())
val = 'Chinese'
ind=val_list.index(val)
print(key_list[ind])
Output: 'CNY'

Of course, the above code can also be reduced to the following line of code:

list(currency_dict.keys())[list(currency_dict.values()).index(val)]

4. Use Loop

Of course, the operation of the above code to obtain the value subscript index from val_list can be replaced by a loop method, and the steps are as follows:

  • Convert the key and value of the dictionary into lists key_list, value_list respectively
  • Loop through the value_list to find the index of the corresponding value
  • Returns the key value of the corresponding index in key_list

code show as below:

key_list=list(currency_dict.keys())
val_list=list(currency_dict.values())
def return_key(val):
    for i in range(len(currency_dict)):
        if val_list[i]==val:
            return key_list[i]
    return("Key Not Found")
print(return_key("Dollar"))
Output: 'USD'

5. Use items()

In the dictionary type, the function items() organizes the elements in the dictionary into key-value pairs. We can achieve the same function as follows:

  • Use items() to iterate over all key-value pairs in the dictionary
  • Compare whether the value is the required value
  • If found, the corresponding key is returned

code show as below:

def return_key(val):
    for key, value in currency_dict.items():
        if value==val:
            return key
    return('Key Not Found')
print(return_key('Euro'))
Output: 'EUR'

6. Using Pandas DataFrames

Converting the dictionary into a DataFrame and then getting the key is currently one of the easiest ways. But this creates new data and is not the most efficient.

The dictionary type is converted to the corresponding DataFrame type code as follows:

df=pd.DataFrame({
    
    'abbr':list(currency_dict.keys()),
                 'curr':list(currency_dict.values())})

The above code stores all the keys in the abbr column in the DataFrame, and stores all the values ​​in the curr column in the DataFrame.

After the above conversion, it is very easy to find the key value next, just execute the following code:

val = 'Pound'
print(df.abbr[df.curr==val])
Output: 2    GBP

Isn't it much simpler. . .
Observe carefully, the above code also returns the corresponding index value, and the returned value is not a string type but a serialized type in pandas, we can use the following statement to convert it to a string type.

df.abbr[df.curr==val].unique()[0]
df.abbr[df.curr==val].mode()[0]
df.abbr[df.curr==val].sum()
Output : 'GBP'

7. Summary

This article introduces several methods of how to obtain the key from the dictionary according to the value in Python, explains each method in detail, and gives the corresponding code implementation.

Have you lost your studies?




insert image description here
Follow the official account "The Way of AI Algorithms" to get more information about AI algorithms.

Follow the official account and reply to dict in the background to get the source code.

Guess you like

Origin blog.csdn.net/sgzqc/article/details/122350596