Get return value python

Get value from dictionary by key with get() in Python

This article describes how to get the value from a dictionary ( dict type object) by the key in Python.

If you want to extract keys by their values, see the following article.

Get value from dictionary with dictGet return value python ( KeyError for non-existent keys)

In Python, you can get the value from a dictionary by specifying the key like dictGet return value python .

d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d['key1']) # val1 

In this case, KeyError is raised if the key does not exist.

# print(d['key4']) # KeyError: 'key4' 

Specifying a non-existent key is not a problem if you want to add a new element.

For more information about adding items to the dictionary, see the following article.

Use in to check if the key exists in the dictionary.

Use dict.get() to get the default value for non-existent keys

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

Specify the key as the first argument. If the key exists, the corresponding value is returned; otherwise, None is returned.

d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d.get('key1')) # val1 print(d.get('key4')) # None 

You can specify the default value to be returned when the key does not exist in the second argument.

print(d.get('key4', 'NO KEY')) # NO KEY print(d.get('key4', 100)) # 100 

The original dictionary remains unchanged.

Источник

Python Dictionary get() Method

The get() method returns the value of the item with the specified key.

Syntax

Parameter Values

Parameter Description
keyname Required. The keyname of the item you want to return the value from
value Optional. A value to return if the specified key does not exist.
Default value None

More Examples

Example

Try to return the value of an item that do not exist:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python Dictionary get()

The get() method returns the value of the specified key in the dictionary.

Example

scores = < 'Physics': 67, 'Maths': 87, 'History': 75 >
result = scores.get('Physics')
print(scores) # 67

Syntax of Dictionary get()

get() Parameters

get() method takes maximum of two parameters:

  • key — key to be searched in the dictionary
  • value (optional) — Value to be returned if the key is not found. The default value is None .

Return Value from get()

  • the value for the specified key if key is in the dictionary.
  • None if the key is not found and value is not specified.
  • value if the key is not found and value is specified.

Example 1: How does get() work for dictionaries?

person = 
print('Name: ', person.get('name'))
print('Age: ', person.get('age')) # value is not provided
print('Salary: ', person.get('salary'))
# value is provided print('Salary: ', person.get('salary', 0.0))
Name: Phill Age: 22 Salary: None Salary: 0.0

Python get() method Vs dictGet return value python to Access Elements

get() method returns a default value if the key is missing.

However, if the key is not found when you use dictGet return value python , KeyError exception is raised.

person = <> # Using get() results in None 
print('Salary: ', person.get('salary'))
# Using [] results in KeyError print(person['salary'])
Salary: None Traceback (most recent call last): File "", line 7, in print(person['salary']) KeyError: 'salary'

Источник

Python Dictionary Get: Step-By-Step Guide

The Python dictionary get() method returns the value associated with a specific key. get() accepts two arguments: the key for which you want to search and a default value that is returned if the key is not found.

Retrieving a value for a specified key in a dictionary is a common operation when you’re working with dictionaries. For instance, you may be a tea shop owner and want to retrieve how many orders you had for white tea.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

That’s where the Python dictionary get—dict.get()—method comes in: it returns the value for a specified key in a dictionary.

This method will only return a value if the specified key is present in the dictionary, otherwise it will return None.

In this tutorial, we will explore Python’s built-in dict.get() method and how you can use it to retrieve specific values from Python dictionaries. In addition, we’ll walk through examples of the dict.get() method in real programs to explain how it works in more depth.

Python Dictionary Refresher

Python dictionaries map keys to values and create key-value pairs that can be used to store data. Dictionaries are often used to hold related data. For instance, a dictionary could act as the record of a student at a school or information about a book in a library. I want to give the writers direct feedback so that they can improve instead of just fixing errors.

Here’s an example of a dictionary in Python that holds information about a specific tea sold in a tea shop:

The words to the left of the colons are dictionary keys, which in the above example are: supplier, name, boxes_in_stock, and loose_leaf.

Python Dictionary get() Method

The Python dictionary get() method retrieves a value mapped to a particular key. get() will return None if the key is not found, or a default value if one is specified.

The syntax for the dict.get() method in Python is as follows:

dictionary_name.get(name, value)

The dict.get() method accepts two parameters:

  • name is the name of the key whose value you want to return. This parameter is required.
  • value is the value to return if the specified key does not exist. This defaults to None. This parameter is optional.

You can retrieve items from a dictionary using indexing syntax. As we’ll discuss later in this guide, this can sometimes be counterintuitive.

Most beginners learn indexing first. But, once you know how to use get() you’ll probably find yourself using it more often than dictionary indexing to retrieve a value.

Get Values from Dictionary in Python: Example

Let’s walk through an example to demonstrate the dict.get() method in action. Say that we are operating a tea house, and we want to see how many people ordered matcha_green_tea last month.

This data is part of a dictionary that stores the names of teas as keys. The number of people who ordered specific teas are stored as values.

We could use the following code to retrieve how many people ordered matcha_green_tea:

teas = < 'english_breakfast': 104, 'matcha_green_tea': 26, 'green_tea': 29, 'decaf_english_breakfast': 51, 'assam': 48 >matcha = teas.get('matcha_green_tea') print(matcha)

At the start of our code, we define a Python variable called teas. This dictionary stores information about tea orders in our tea house.

Then, we use the dict.get() method on our teas dictionary to retrieve the value associated with the matcha_green_tea key. Finally, we print out the value to the console using a Python print() statement.

Let’s consider another example. Let’s say that we have a dictionary for each tea that we sell. These dictionaries contain information about their respective teas, including:

  • Who the supplier is.
  • What we name the tea.
  • How many boxes we have in stock.
  • Whether it is loose-leaf.

The following is our dictionary for the black tea we sell:

Suppose we want to find out whether our black tea is stored as a loose-leaf tea. We could do so using this code:

get_loose_leaf = black_tea.get('loose_leaf') print(get_loose_leaf)

We use the dict.get() method to retrieve the value of loose_leaf in the black_tea dictionary. The fact that our code returns True tells us that our black tea is stored as a loose-leaf tea. We would receive a None value if our tea did not exist in the dictionary.

Python Dictionary get(): Default Value

The dict.get() method accepts an optional second parameter. This parameter specifies the value that should be returned if a key cannot be found within a dictionary. This lets you change the default response of None if a value is not found.

So, let’s say that we want to retrieve taste_notes from a dictionary that stores information about the black tea our tea house stocks. We only just hired our tea taster tasked with writing those descriptions, so they don’t exist for all teas yet. Tasting notes do not exist for our black tea.

To avoid our program returning None, we want our code to return a notification message. This message should inform us that the taste notes are not available for that tea yet.

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

The below program retrieves taste_notes from a dictionary containing information about our black tea. Our program returns a message if the taste notes are not available:

black_tea = < 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True >get_loose_leaf = black_tea.get('taste_notes', 'Taste notes are not available for this tea yet.') print(get_loose_leaf)

Our black_tea dictionary does not contain a value for the key taste_notes, so our program returns the following message:

Taste notes are not available for this tea yet.

Python Dictionary get() vs. dictGet return value python

One common method used to access a value in a dictionary is to reference its value using the dictGet return value python syntax.

The difference between the dictGet return value python syntax and dict.get() is that if a key is not found using the dictGet return value python syntax, a KeyError is raised. If you use dict.get() and a key is not found, the code will return None (or a custom value, if you specify one).

Here’s what happens if we try to use the dictGet return value python syntax to retrieve taste_notes from a dictionary that lacks that key:

black_tea = < 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True >print(black_tea['taste_notes'])

Because taste_notes is not present in our black_tea dictionary, our code returns the following error:

Conclusion

The dict.get() method is used in Python to retrieve a value from a dictionary. dict.get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.

You can also use the dictGet return value python syntax to retrieve a value from a dictionary. If you use the dictGet return value python syntax and the program cannot find the key you specify, the code will return a KeyError. Because this syntax returns an error, using the dict.get() method is often more appropriate.

Now you’re ready to start retrieving values from a Python dictionary using dict.get() like a pro! For guidance on Python courses and learning resources, check out our How to Learn Python guide.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

Читайте также:  Html image absolute bottom
Оцените статью