×

Find key from value in dictionary python

Python:

Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programing language, as its syntax is very simple to write and easy to understand for a beginner programmer. It is used in many popular companies worldwide like google, uber, Instagram, amazon, etc. Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in libraries that can be imported easily and used to perform many different operations. In the year 1989, Guido van Rossum is the one who introduced python programming language. Python is widely used in machine learning, and data science departments deal with heavy data. It is also used in web applications; web applications like the Django and Flask frameworks are created using python. The python programming language is straightforward to learn by anyone. Compared to any programming language, the syntax in python is much easier. Many colleges and institutions have introduced python in their syllabus so that the students need to learn python. The biggest advantage of the python programming language is that it has a good collection of libraries that are widely used in machine learning, web frameworks, test frameworks, multimedia, image processing, and many more applications.

Dictionaries in python

Dictionaries in python in python are considered to be a collection with key values. It is used to store the data values of a map compared to other data types, which have only one value as the element but more than one value as an element. Now let us look into an example of how a dictionary is in python program programming language. Dictionary has a key: value format. The key value is provided in the python dictionary to make it more optimized. Now let's look into an example code in a python programming language to create a dictionary and print it.

Example code:

# # # creating a dictionary in python programming language
D = { 1 : 'ironman' , 2 : 'captainamerica' , 3: 'thor' , 4 : 'blackpanther' , 5 : 'vision'}
# # # printing the created dictionary
print( D )

Output

 { 1 : ‘ironman’ , 2 : ‘captainamerica’ , 3: ‘thor’ , 4 : ‘blackpanther’ , 5 : ‘vision’ }

Creating a dictionary in a python programming language is similar to having elements in the curly braces ( { } ) which are separated by a comma (, ). Generally, a dictionary has two values. One is considered a key, and the other is its corresponding key: value. The values in the dictionary can be of any data type and can be repeated as often as required, but the keys are not supposed to be repeated, and these are immutable, which means once they are declared, they cannot be changed. The keys of the dictionary are case-sensitive. Now let's understand in a better way how to create a dictionary with integer keys and different datatypes as keys.

Example code

# # # creating a a dictionary in pyhton programming language with integer as keys
D = { 1 : 'ironman' , 2 : 'captainamerica' , 3: 'thor' , 4 : 'blackpanther' , 5 : 'vision'}
# # # printing the created dictionary
print("\nusing integer as keys the dictionary is : ")
print( D )
D = {  'name' : 'ravan' , 1 : [ 2, 3,  4, 5, 6 , 7, 8, 9, 0] }
print("\n using mixed keys the dictionary is: ")
print( D )

Output:

using integer as keys the dictionary is :
 { 1 : ‘ironman’ , 2 : ‘captainamerica’ , 3: ‘thor’ , 4 : ‘blackpanther’ , 5 : ‘vision’ }
using mixed keys the dictionsry is:
{  ‘name’ : ‘ravan’ , 1 : [ 2, 3,  4, 5, 6 , 7, 8, 9, 0 ]

We can also create a dictionary by using a built function called dict( ). one can create an empty dictionary by simply using empty curly braces { }. now let's look-see the example code of how to create an empty dictionary with the use of a built I function called dict( ).

Example code:

# # # creating an empty dictionary
D = { }
# #  # printng the empty dictionary
print('\nthe empty dictionary is: ' )
print( D )
# # # creating a dictonary with the help of built in functoin called dict( )
D = { 1 : 'ironman' , 2 : 'captainamerica' , 3: 'thor' , 4 : 'blackpanther' , 5 : 'vision'}
print( '\ndictionary with the help of dict( ): ' )
print( D )

Output

the empty dictionary is:
{ }
dictoinary with the help of dict( ): 
{ 1 : ‘ironman’ , 2 : ‘captainamerica’ , 3: ‘thor’ , 4 : ‘blackpanther’ , 5 : ‘vision’ }

Now we can create a dictionary; let's see how to find the key from the value in the dictionary in a python programming language.

Finding key from value in dictionary

Let's find or extract the key from the dictionary using the value. First, let's discuss the method to get the key value using the list comprehension method. This method consists of brackets that have the expression; it is executed for each element in the dictionary along the for loop, which is iterated over each element in the python list to find the key from the value in the python dictionary.

Example code:

D = { 1 : 'ironman' , 2 : 'captainamerica' , 3: 'thor' , 4 : 'blackpanther' , 5 : 'vision'}
V = { I for I in D if  D[ I ] == 'captainamerica' }
print( "key by value:" , V )

Output:

Key by value: { 2 }

Now lets Discuss the method using the list.index( ). This method returns the index as the value in a list.in this method, it is found two different lists of keys and values. Then using, the position of the value from the V_list key is fetched. The key at any position N in the key_list has the corresponding value at the position N in the V_list. Now lets us look into an example code.

Example code :

# # # creating a dictionary
D = { 'rohith' : 100 , 'vardhan' : 200 , 'taimur' : 300 , 'kiran' : 400 , 'ravi' : 500 , 'ram' : 600 }
# # # printing the crreated dictionary
print( D )
Key_list = list( D.keys( ) )
V_list = list( D.values( ) )
# # # printing the key having the value of 300
pos = V_list.index( 300 )


print( Key_list[ pos ] )

Output

 { “rohith” : 100 , “vardhan” : 200 , “taimur” : 300 , “kiran” : 400 , “ravi” : 500 , “ram” : 600 }
taimur

Now let's look into another method, finding the key for value using dict.item( )

In this method, we fetch the key from a value by matching the values using the    dict.item( ) and then get the corresponding key value for the given value. Now let us look at the example program to understand it better.

Example code:

# # # creating a dictionary
D = { 'rohith' : 100 , 'vardhan' : 200 , 'taimur' : 300 , 'kiran' : 400 , 'ravi' : 500 , 'ram' : 600 }
print( D )
# # # creating a function to return key of any value
def get_key( val ) :
               for key, value in D.items( ) :
                      if val == value :
                                return key
               return "the key doesn’t exist "
print( get_key( 200 ) )
print( get_key( 300 ) )

Output

{ “rohith” : 100 , “vardhan” : 200 , “taimur” : 300 , “kiran” : 400 , “ravi” : 500 , “ram” : 600 }
vardhan
taimur

Related Topics

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.