Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Get Key by Value in The Dictionary

#1
Get Key by Value in The Dictionary

<div><div id="ez-toc-container" class="ez-toc-v2_0_18 counter-hierarchy counter-decimal ez-toc-light-blue">
<div class="ez-toc-title-container">
<p class="ez-toc-title">Table of Contents</p>
<p><span class="ez-toc-title-toggle"><a class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" style="display: none;"><i class="ez-toc-glyphicon ez-toc-icon-toggle"></i></a></span></div>
<nav>
<ul class="ez-toc-list ez-toc-list-level-1">
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-1" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Solution_1_Using_dictitems" title="Solution 1: Using dict.items()">Solution 1: Using dict.items()</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-2" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Solution_2_Using_keys_values_and_index" title="Solution 2: Using keys(), values() and index()">Solution 2: Using keys(), values() and index()</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-3" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Solution_3_Interchanging_the_Keys_and_Values" title="Solution 3: Interchanging the Keys and Values ">Solution 3: Interchanging the Keys and Values </a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-4" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Solution_4_Using_zip" title="Solution 4: Using zip()">Solution 4: Using zip()</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-5" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Solution_5_Using_Pandas" title="Solution 5: Using Pandas">Solution 5: Using Pandas</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-6" href="https://blog.finxter.com/get-key-by-value-in-the-dictionary/#Conclusion" title="Conclusion">Conclusion</a></li>
</ul>
</nav>
</div>
<p><strong>Problem Statement:</strong> How to get a key by its value in a dictionary in Python </p>
<p><strong>Example: </strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030} # Some Way to extract the Key 'Bob' using its value 2020</pre>
<p>We have a clear idea about the problem now. So without further delay, let us dive into the solutions to our question.</p>
<h2><strong>Solution 1:</strong><strong> </strong><strong>Using dict.items()</strong></h2>
<p class="has-global-color-8-background-color has-background"><strong>Approach: </strong>One way to solve our problem and extract the key from a dictionary by its value is to use the <code>dict.items()</code>. The idea here is to create a function &nbsp;that takes the provided value as an input and compares it to all the values present in the dictionary. When we get the matching value, we simply return the key assigned to the value.</p>
<p><strong>Solution:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030} # Function that fetches key from value
def get_key(v): for key, value in employee.items(): # return the key which matches the given value if v == value: return key return "The provided key is not present in the dictionary" # Passing the keys to the function
print("Employee ID - 2020 \nName - ", get_key(2020))</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>Employee ID - 2020 Name - Bob</code></pre>
<p><strong>Note: </strong><code>dict.items()</code> is a dictionary method in Python that returns a view object. The returned view object contains a list of tuples that comprises the key-value pairs in the dictionary.&nbsp;Any changes made to the dictionary will also be reflected in the view object.</p>
<p><strong>Example:</strong> The following example demonstrates how the <code>dict.items()</code> method works.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
item = employee.items()
employee['Tom'] = '4040'
print(item)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dict_items([('Sam', 1010), ('Bob', 2020), ('Rob', 3030), ('Tom', '4040')])</pre>
<h2><strong>Solution 2: <strong>Using keys(), values() and index()</strong></strong></h2>
<p class="has-global-color-8-background-color has-background"><strong>Approach: </strong>Another workaround to solve our problem is to extract the keys and values of the dictionary separately in two different lists with the help of the <code>keys()</code> and <code>values()</code> methods. Then find the index/position of the given value from the list that stores the values with the help of the <code>index()</code> method. Once the index is found, you can easily locate the key corresponding to this index from the list that stores all the keys.</p>
<p><strong>Solution:</strong> Please follow the comments within the code to get an insight of the solution.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# store all the keys in a list
key = list(employee.keys())
# store all the values in another list
val = list(employee.values())
# find the index of the given value (2020 in this case)
loc = val.index(2020)
# Use the index to locate the key
print(key[loc])</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Bob</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>keys()</code> is a dictionary method that returns a view object that contains the keys of the dictionary in a list.</li>
<li><code>values()</code> is a dictionary method that returns a view object consisting of the values in the dictionary within a list.</li>
<li>The <code>index()</code> method is used to return the index of the specified item in a list. The method returns only the first occurrence of the matching item.</li>
</ul>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
li = ['Lion', 'Dog', 'Cat', 'Mouse', 'Dog']
key = list(employee.keys())
val = list(employee.values())
loc = li.index('Dog')
print(f"Keys: {key}")
print(f"Values: {val}")
print(f"Index: {loc}")</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Keys: ['Sam', 'Bob', 'Rob']
Values: [1010, 2020, 3030]
Index: 1</pre>
<h2><strong>Solution 3: Interchanging the Keys and Values </strong></h2>
<p class="has-global-color-8-background-color has-background"><strong>Approach: </strong>The given problem can be resolved using a single line of code. The idea is to use a dictionary comprehension that reverses the keys and values. This means the keys in the original dictionary become the values in the newly created dictionary while the values in the original dictionary become the keys in the newly created dictionary. Once you have interchanged the keys and values, you can simply extract the key by its value.va</p>
<p><strong>Solution:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
res = dict((val, key) for key, val in employee.items())
print("Original Dictionary: ", employee)
print("Modified Dictionary: ", res)
# using res dictionary to find out the required key from employee dictionary
print(res[2020])</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Original Dictionary: {'Sam': 1010, 'Bob': 2020, 'Rob': 3030}
Modified Dictionary: {1010: 'Sam', 2020: 'Bob', 3030: 'Rob'}
Bob</pre>
<p><strong>Explanation: </strong></p>
<ul>
<li><code data-enlighter-language="generic" class="EnlighterJSRAW"><code>employee</code></code> dictionary has Name and Employee ID as Key-Value pairs. </li>
<li><code>res</code> dictionary interchanges the keys and values of the <code>employee</code> dictionary. Therefore, <code>res</code> now has Employee ID and Name as Key-Value pairs.</li>
<li>Since we need to extract the name corresponding to an Employee ID. We can simply get that from the <code>res</code> dictionary with the help of the key which in this case is the Employee ID.</li>
</ul>
<h2><strong>Solution 4: Using zip()</strong></h2>
<p class="has-global-color-8-background-color has-background">Considering that the values in the given dictionary are unique, you can solve the problem with a single line of code. The idea is to use the <code>keys()</code> and <code>values()</code> dictionary methods to extract the keys and values from the dictionary and then tie them together with the help of the <code>zip()</code> method to produce a dictionary. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
name = dict(zip(employee.values(), employee.keys()))[2020]
print(f'Name: {name} \nEmployee ID: 2020')</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name: Bob Employee ID: 2020</pre>
<h2><strong>Solution 5: Using Pandas</strong></h2>
<p class="has-global-color-8-background-color has-background">We can also opt to use the Pandas DataFrame to get the key by its value. In this approach, first, we will convert the given dictionary into a data frame.&nbsp; Further, we can name the column with the keys as “<code>key</code>” and the columns with the values as “<code>value</code>“. To get the key by the given value, we have to return the value from the ‘<code>key</code>‘ column from the row where the value of the ‘<code>value</code>‘ column is the required value.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Importing the pandas module
import pandas as pd # Given dictionary
employee = {"Sam": 1010, "Bob": 2020, "Rob": 3030}
# list to store the keys from the dictionary
key = list(employee.keys())
# list to store the values from the dictionary
val = list(employee.values())
# Converting the dictionary into a dataframe
df = pd.DataFrame({'key': key, 'value': val})
print("The data frame:")
print(df)
# Given Value
v = 2020
print("The given value is", v)
# Searching for the key by the given value
k = (df.key[df.value == v].unique()[0])
print("The key associated with the given value is:", k)</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">The data frame: key value
0 Sam 1010
1 Bob 2020
2 Rob 3030
The given value is 2020
The key associated with the given value is: Bob</pre>
<p><strong>Note:</strong> <code>df.key[df.value == v].unique()[0])</code> –&gt; We have to use the unique method in this line to avoid the index from getting printed. While using the panda’s data frame, the output is not in the string format, but it is a pandas series object type. Hence, we need to convert it using the unique or sum() method. Without the unique method, the output will also consider the index of the data frame column.</p>
<h2><strong>Conclusion</strong></h2>
<p>That’s all about how to get a key by the value in the dictionary. I hope you found it helpful. Please&nbsp;<strong><a rel="noreferrer noopener" href="https://blog.finxter.com/" target="_blank">stay tuned&nbsp;</a></strong>and&nbsp;<strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a>&nbsp;</strong>for more interesting tutorials. Happy Learning!</p>
</div>


https://www.sickgaming.net/blog/2022/04/...ictionary/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016