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
YouTube Tutorial by AuthorView Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container. Let’s discuss certain ways in which this can be performed.
Method 1: Extract specific keys from dictionary using dictionary comprehension + items[]
This problem can be performed by reconstruction using the keys extracted through the items function that wishes to be filtered and the dictionary function makes the desired dictionary.
Python3
test_dict
=
{
'nikhil'
:
1
,
"akash"
:
2
,
'akshat'
:
3
,
'manjeet'
:
4
}
print
[
"The original dictionary : "
+
str
[test_dict]]
res
=
{key: test_dict[key]
for
key
in
test_dict.keys[]
& {
'akshat'
,
'nikhil'
}}
print
[
"The filtered dictionary is : "
+
str
[res]]
Output :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1} The filtered dictionary is : {'akshat': 3, 'nikhil': 1}
Method 2: Extract specific keys from the dictionary using dict[]
The dict[] function can be used to perform this task by converting the logic performed using list comprehension into a dictionary.
Python3
test_dict
=
{
'nikhil'
:
1
,
"akash"
:
2
,
'akshat'
:
3
,
'manjeet'
:
4
}
print
[
"The original dictionary : "
+
str
[test_dict]]
res
=
dict
[[k, test_dict[k]]
for
k
in
[
'nikhil'
,
'akshat'
]
if
k
in
test_dict]
print
[
"The filtered dictionary is : "
+
str
[res]]
Output :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1} The filtered dictionary is : {'akshat': 3, 'nikhil': 1}