How To Get Value From Dictionary In Python
How to Extract Key from Python Dictionary using Value
Four methods to extract keys from python dictionary given value
It is straight-forward to extract value if we have key, like unlocking a lock with a key. However, the vice versa is not as simple, like "unkeying the key with a lock", maybe!
Sometimes extracting keys become important especially when the key and value has a one-to-one relationship. That is, when either of them is unique and hence can act as the key.
Before getting into the various methods, first we will create a dictionary for the purpose of illustration.
currency_dict is the dictionary with currency abbreviations as keys and currency names as value.
currency_dict={'USD':'Dollar',
'EUR':'Euro',
'GBP':'Pound',
'INR':'Rupee'}
If you have the key, getting the value by simply adding the key within square brackets.
For example, currency_dict['GBP'] will return 'Pound'.
Method 1 : Using List
Step 1: Convert dictionary keys and values into lists.
Step 2: Find the matching index from value list.
Step 3: Use the index to find the appropriate key from key list.
key_list=list(currency_dict.keys())
val_list=list(currency_dict.values())
ind=val_list.index(val)
key_list[ind] Output: 'GBP'
All the three steps can be combined in a single step as below:
list(currency_dict.keys())[list(currency_dict.values()).index(val)]
Method 2: Using For Loop
Method 1 can be slightly modified using a for loop as below:
Step 1: Convert dictionary keys and values into lists.
Step 2: Iterate through all values in value list to find the required value
Step 3: Return the corresponding key from the key list.
def return_key(val):
for i in range(len(currency_dict)):
if val_list[i]==val:
return key_list[i]
return("Key Not Found") return_key("Rupee") Output: 'INR'
Method 3: Using items()
items() keep dictionary elements as key-value pair.
Step 1: Iterate through all key-value pairs in item().
Step 2: Find the value which match the required value
Step 3: Return the key from the key-value pair.
def return_key(val):
for key, value in currency_dict.items():
if value==val:
return key
return('Key Not Found') return_key('Dollar') Output: 'USD'
Method 4: Using Pandas DataFrame
Getting the keys from after converting into a DataFrame is in my opinion the simplest and easy to understand method.
However it is not the most efficient one, which in my opinion would be the one-liner in Method 1.
A dictionary can be converted into a pandas DataFrame as below:
df=pd.DataFrame({'abbr':list(currency_dict.keys()),
'curr':list(currency_dict.values())})
All keys are in the column 'abbr' and all values are in 'curr' column of DataFrame 'df'.
Now finding the value is very easy, just return the value from 'abbr' column from the row where value of 'curr' column is the required value.
df.abbr[df.curr==val] Output: 2 GBP
Much simpler than how it sounds!
Note that the output contains index as well. The output is not in string format but it is a pandas Series object type.
The series object can be converted to string using many options, few are as follows:
df.abbr[df.curr==val].unique()[0]
df.abbr[df.curr==val].mode()[0]
df.abbr[df.curr==val].sum() Output : 'GBP'
Resources
The code for this article is available in my GitHub Repo.
You can check out my YouTube video if you are more interested in the visual format
How To Get Value From Dictionary In Python
Source: https://towardsdatascience.com/how-to-extract-key-from-python-dictionary-using-value-2b2f8dd2a995
Posted by: harkinsstroffeld89.blogspot.com
0 Response to "How To Get Value From Dictionary In Python"
Post a Comment