×

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

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Python Redis Example

Introduction: Redis, representing Distant Word reference Server, is a kind of key-esteem NoSQL server. Redis is intended to help circle capacity for determination, holding information after power is stopped, and stores information...

5 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.