How to get a value for a given key from a Python dictionary? (2024)

How to get a value for a given key from a Python dictionary? (1)

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

PythonProgrammingServer Side Programming

';

In this article, we will show you how to get a value for the given key from a dictionary in Python. Below are the 4 different methods to accomplish this task −

  • Using dictionary indexing

  • Using dict.get() method

  • Using keys() Function

  • Using items() Function

Assume we have taken a dictionary containing key-value pairs. We will return the value for a given key from a given input dictionary.

Method 1: Using dictionary indexing

In Python, we can retrieve the value from a dictionary by using dict[key].

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input dictionary

  • Get the value of a given key from the input dictionary by passing the key value to the input dictionary in [] brackets.

  • print the resultant value for a given key.

Example 1

The following program returns the index of the value for a given key from an input dictionary using the dict[key] method −

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# Printing the value of key 10 from a dictionaryprint("The value of key 10 from dictionary is =", demoDictionary[10])

Output

The value of key 10 from dictionary is = TutorialsPoint

If the key does not exist in a given input dictionary, a KeyError is raised.

Example 2

In the below code, the key 'hello' is not present in the input list. So, when we try to print the value of the key 'hello', a KeyError is returned. −

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# Printing the value of key 'hello' from a dictionary# A KeyError is raised as the hello key is NOT present in the dictionaryprint("The value of key 'hello' from a dictionary:", demoDictionary['hello'])

Output

Traceback (most recent call last): File "main.py", line 6, in  print("The value of key 'hello' from a dictionary:", demoDictionary['hello'])KeyError: 'hello'

Handling the KeyError

The following code handles the KeyError returned in the above code using the try-except blocks −

Example

Here the except block statements will get executed if any error occurs. −

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# Handling KeyError using try-except blockstry: print(demoDictionary['hello'])except KeyError: print("No, The key for Value 'Hello' does not exist in the dictionary. Please check")

Output

No, The key for Value 'Hello' does not exist in the dictionary. Please check

Method 2: Using dict.get() method

We can get the value of a specified key from a dictionary by using the get() method of the dictionary without throwing an error, if the key does not exist.

As the first argument, specify the key. If the key exists, the corresponding value is returned; otherwise, None is returned.

Example 1

The following program returns the index of the value for a given key from an input dictionary using dict.get() method −

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# Printing the value of key 10 from a dictionary using get() methodprint("The value of key 10 from a dictionary:", demoDictionary.get(10))# Printing the value of key 'hello' from a dictionary# As the hello key does not exist in the dictionary, it returns Noneprint("The value of key 'hello' from a dictionary:", demoDictionary.get('hello'))

Output

The value of key 10 from a dictionary: TutorialsPointThe value of key 'hello' from a dictionary: None

In the second argument, you can define the default value to be returned if the key does not exist.

Example 2

The following program returns the user-given message which is passed as a second argument if the key does not exist in the dictionary using dict.get() method −

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# Printing the value of key 'hello' from a dictionary# As the hello key does not exist in the dictionary, it returns the user-given messageprint("The value of key 'hello' from a dictionary:", demoDictionary.get('hello', "The Key does not exist"))

Output

The value of key 'hello' from a dictionary: The Key does not exist

Method 3: Using keys() Function

The following program returns the index of the value for a given key from an input dictionary using the keys() method

Following are the Algorithm/steps to be followed to perform the desired task −

  • Traverse in the dictionary keys using the keys() function(the dict. keys() method provides a view object that displays a list of all the keys in the dictionary in order of insertion).

  • Check if the given key is equal to the iterator value and if it is equal then print its corresponding value

Example

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}# enter the key for which the value to be obtainedgivenkey= 10# Traversing the keys of the dictionaryfor i in demoDictionary.keys(): # checking whether the value of the iterator is equal to the above-entered key if(i==givenkey): # printing the value of the key print(demoDictionary[i])

Output

TutorialsPoint

Method 4: Using items() Function

Example

The following program returns the index of the value for a given key from an input dictionary using the items() method

# input dictionarydemoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}givenkey= 12# Traversing in the key-value pairs of the dictionary using the items() functionfor key,val in demoDictionary.items(): # checking whether the key value of the iterator is equal to the above-entered key if(key==givenkey): print(val)

Output

Python

Conclusion

We learned how to get the value of the dictionary key using four different methods in this article. We also learned how to deal with errors when a key does not exist in the dictionary.

Vikram Chiluka

Updated on: 31-Oct-2023

30K+ Views

  • Related Articles
  • How to print a value for a given key for Python dictionary?
  • Get key from value in Dictionary in Python
  • How to remove a key from a python dictionary?
  • Accessing Key-value in a Python Dictionary
  • Add a key value pair to dictionary in Python
  • Swift Program to Get key from Dictionary using the value
  • Python Program to print key value pairs in a dictionary
  • Get key with maximum value in Dictionary in Python
  • Python - Value Summation of a key in the Dictionary
  • How to get a key/value data set from a HTML form?
  • Add an item after a given Key in a Python dictionary
  • How to extract subset of key-value pairs from Python dictionary object?
  • How to check if a key exists in a Python dictionary?
  • Python program to extract key-value pairs with substring in a dictionary
  • How to search Python dictionary for matching key?
Kickstart Your Career

Get certified by completing the course

Get Started

How to get a value for a given key from a Python dictionary? (31)

Advertisem*nts

';

How to get a value for a given key from a Python dictionary? (2024)
Top Articles
Faraday Future Intelligent Electric Inc. (FFIE) Stock Forecast & Price Prediction 2025, 2030 | CoinCodex
Deemed dividends - Canada.ca
Drury Inn & Suites Bowling Green
Forozdz
Www.1Tamilmv.cafe
Devon Lannigan Obituary
Mountain Dew Bennington Pontoon
Greedfall Console Commands
Identifont Upload
Okatee River Farms
Music Archives | Hotel Grand Bach - Hotel GrandBach
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
Craigslist Dog Kennels For Sale
Walmart Windshield Wiper Blades
Houses and Apartments For Rent in Maastricht
Las 12 mejores subastas de carros en Los Ángeles, California - Gossip Vehiculos
Lehmann's Power Equipment
Missouri Highway Patrol Crash
Accuweather Mold Count
Heart and Vascular Clinic in Monticello - North Memorial Health
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
O'Reilly Auto Parts - Mathis, TX - Nextdoor
Receptionist Position Near Me
Sensual Massage Grand Rapids
Table To Formula Calculator
Ullu Coupon Code
Jamielizzz Leaked
Dairy Queen Lobby Hours
Desales Field Hockey Schedule
417-990-0201
Word Trip Level 359
Panchang 2022 Usa
Minecraft Jar Google Drive
Sedano's Supermarkets Expands to Orlando - Sedano's Supermarkets
Car Crash On 5 Freeway Today
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Hermann Memorial Urgent Care Near Me
Ljw Obits
Eleceed Mangaowl
SOC 100 ONL Syllabus
Boggle BrainBusters: Find 7 States | BOOMER Magazine
Pinellas Fire Active Calls
Rs3 Bis Perks
Letter of Credit: What It Is, Examples, and How One Is Used
Karen Wilson Facebook
Candise Yang Acupuncture
Phmc.myloancare.com
La Qua Brothers Funeral Home
Erica Mena Net Worth Forbes
Zom 100 Mbti
Die 10 wichtigsten Sehenswürdigkeiten in NYC, die Sie kennen sollten
Selly Medaline
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 6422

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.