Python dict get method

Python dictionary get() method [With Examples]

In this Python article, we will explore the Python dictionary get() method, which is a valuable tool for safely accessing dictionary values. We will discuss its syntax, usage, and some practical examples to help you utilize this method effectively.

Below are the topics that we are doing to discuss in this article:

  • Introduction to Python Dictionary get() method
  • Syntax of the get() method
  • Purpose and use cases of the get() method

Dictionary get() method in Python

The get() method in a Python dictionary is a built-in function that allows you to safely access a value from a dictionary using a key without raising a KeyError if the key is not found. Instead, it returns a default value provided by you, or None if no default value is specified.

The syntax for the get() method is as follows:

  • dictionary : The dictionary we want to access.
  • key : The key for which we want to retrieve the corresponding value.
  • default (optional): The value to be returned if the specified key is not found in the dictionary. If not provided, it defaults to None.

Return Value:

The method returns the value associated with the specified key if it exists in the Python dictionary; otherwise, it returns the default value provided.

get() method in Python Dictionary Examples

Let’s take a look at some examples of using the get() method.

Example#1 Basic Usage

presidents_terms = print(presidents_terms.get("George Washington", "Unknown")) print(presidents_terms.get("James Monroe", "Unknown")) 

In this example, we have a Python dictionary containing the names of US presidents as keys and their term years as values.

Using the get() method, we can safely retrieve the term years for a given president, or return «Unknown» if the president is not in the dictionary.

Python dictionary get method

Example#2 Using get() with a Default Value

state_capitals = print(state_capitals.get("California", "Not Found")) print(state_capitals.get("Florida", "Not Found")) 

In this example, we have a Python dictionary of US states and their capitals. By using the get() method, we can look up the capital of a given state, or return «Not Found» if the state is not in the dictionary.

Python dictionary get method example

Example#3 Using get() Without a Default Value

city_population = print(city_population.get("New York")) print(city_population.get("Houston")) 

Here, we have a Python dictionary of US cities and their populations. Using the get() method, we can retrieve the population of a given city, or return None if the city is not in the dictionary.

Dictionary get method in Python

Example#4 Counting Word Frequency

text = "Python is easy to learn. Python is a powerful language." word_frequency = <> for word in text.split(): word_frequency[word] = word_frequency.get(word, 0) + 1 print(word_frequency)

In this example, we use the Python get() method to count the frequency of each word in a given text. By initializing the word frequency to 0 using the get() method, we can easily update the frequency count for each word in the Python dictionary.

Читайте также:  Quotes to Scrape

Dictionary get method in Python example

Conclusion

The Python dictionary get() method is a powerful and convenient way to access values in a dictionary. By using the get() method, you can avoid KeyError exceptions, improve code readability, and make your code more robust.

You may also like to read the following articles:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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.

Источник

Основы метода get() в Python

Основы метода get() в Python

В Python словари представляют собой структуры данных, которые хранят информацию в форме пар «ключ-значение». Они предлагают несколько методов для манипуляции и взаимодействия с их данными. Один из таких методов — get() . Этот метод позволяет извлечь значение по заданному ключу, без риска вызвать исключение, если такого ключа нет в словаре.

Синтаксис

Метод get() словаря принимает два аргумента:

dictionary.get(key, default_value=None)
  • key — ключ, значение которого мы хотим получить. Это обязательный аргумент.
  • default_value — значение, которое вернется, если ключ не найден в словаре. Это необязательный аргумент. Если он не указан, метод вернет None .

Примеры использования метода get()

Извлечение значения по ключу

Самый простой пример использования метода get() — это получение значения по заданному ключу.

my_dict = value = my_dict.get('b') print(value) # вывод: 2

Здесь мы извлекаем значение, соответствующее ключу b , с помощью метода get() . Этот метод возвращает значение, связанное с ключом, если ключ существует в словаре.

Указание значения по умолчанию

Метод get() позволяет указать значение по умолчанию, которое будет возвращено, если ключ не найден.

my_dict = value = my_dict.get('d', 4) print(value) # вывод: 4

В этом примере мы пытаемся получить значение для ключа d . Поскольку в словаре нет ключа d , метод get() возвращает значение по умолчанию, которое мы указали — 4.

Читайте также:  Field length in javascript

Обработка отсутствующих ключей

Одно из главных преимуществ использования метода get() заключается в его способности безопасно обрабатывать ситуации, когда ключ отсутствует в словаре. Если бы мы попытались получить доступ к значению по отсутствующему ключу напрямую, Python выдал бы исключение KeyError .

my_dict = value = my_dict.get('d') print(value) # вывод: None

Здесь мы пытаемся получить значение для ключа d , которого нет в словаре. Вместо того чтобы вызвать исключение KeyError , метод get() просто возвращает None .

Заключение

Метод get() предоставляет безопасный способ получения доступа к значениям словаря в Python. Он избегает возможности возникновения исключения KeyError , предлагая вместо этого возвращать значение по умолчанию при отсутствии ключа. Это делает его очень полезным инструментом при работе со словарями, особенно когда нет гарантии наличия всех ключей.

Модуль os в Python и его основные функции с примерами использования

Модуль os в Python и его основные функции с примерами использования

Как изменить значение в словаре в Python

Как изменить значение в словаре в Python

Функция slice() в Python: создание объекта среза, представляющий набор индексов, заданных диапазоном

Функция slice() в Python: создание объекта среза, представляющий набор индексов, заданных диапазоном

Простые и эффективные способы замены элемента в списке Python

Простые и эффективные способы замены элемента в списке Python

Конкатенация строк в Python: все сновые способы с примерами

Конкатенация строк в Python: все сновые способы с примерами

nonlocal в Python: что это и когда использовать

nonlocal в Python: что это и когда использовать

Источник

Dictionary Get() Method

Python dict.get() method returns the value corresponding to the specified key.

This tutorial introduces you to get() method of Dictionary class in Python, and its usage, with the help of example programs.

Syntax

The syntax of dictionary get() method is

Parameter Description
key [mandatory] The key for which value has to be fetched from the dictionary.
value [optional] If specified key does not exist, get() returns this value.

Return Value

  • dict.get() returns the value corresponding to the specified key, if present.
  • If the key is not present, and value (second argument) is given, then get() returns this value.
  • If the key is not present, and value (second argument) is not given, then get() returns None.

Examples

1. A simple example for dictionary get()

In this example, we will create a dictionary with some key:value pairs, and use get() method to access values corresponding to the specific keys we provide as arguments.

Python Program

myDict = < 'foo':12, 'bar':14 >print(myDict.get('bar'))

‘bar’ key is present in the dictionary. Therefore, get() method returned the value corresponding to that key.

2. Dictionary get() – Key not present

In this example, we will create a dictionary with some key:value pairs, and use get() method to access value corresponding to a specific key that is not present in the dictionary.

Python Program

myDict = < 'foo':12, 'bar':14 >#key not present in dictionary print(myDict.get('moo'))

The key ‘moo’ is not present in the dictionary. Also, we have not given any second argument to get() method for default value. In these kind of scenarios, as we already see in Return Value section, Dictionary.get() method returns value None of type NoneType.

3. Dictionary get() – Get default value if key not present

You can also tell get() method to return a default value instead of None, if key-value pair is not present for the key specified. Provide the default value as second argument to get() method.

Читайте также:  Website design using css and html

Python Program

myDict = < 'foo':12, 'bar':14 >print(myDict.get('moo', 10))

dict.get() vs Accessing dict using index

Most of the times, you would see or use indexing style of accessing values of a dictionary with key as index. A sample code snippet is

There is a downside of using this style. Which is, when there is no key:value pair for the key we have mentioned, you would get KeyError.

Following is a example demonstrating how using square brackets to get a value corresponding to given key in dictionary ends up with KeyValue error.

Python Program

Traceback (most recent call last): File "example.py", line 6, in print(myDict['moo']) KeyError: 'moo'

So, you may have to explicitly check if the key is present, and then access the dictionary using key as index.

Summary

In this tutorial of Python Examples, we learned how to use Dictionary get() method to access values, with help of well detailed Python programs.

Источник

Словари (dict) и работа с ними. Методы словарей

Python 3 логотип

Сегодня я расскажу о таком типе данных, как словари, о работе со словарями, операциях над ними, методах, о генераторах словарей.

Словари в Python — неупорядоченные коллекции произвольных объектов с доступом по ключу. Их иногда ещё называют ассоциативными массивами или хеш-таблицами.

Чтобы работать со словарём, его нужно создать. Сделать это можно несколькими способами. Во-первых, с помощью литерала:

Во-вторых, с помощью функции dict:

В-третьих, с помощью метода fromkeys:

В-четвертых, с помощью генераторов словарей, которые очень похожи на генераторы списков.

Теперь попробуем добавить записей в словарь и извлечь значения ключей:

  : Как видно из примера, присвоение по новому ключу расширяет словарь, присвоение по существующему ключу перезаписывает его, а попытка извлечения несуществующего ключа порождает исключение. Для избежания исключения есть специальный метод (см. ниже), или можно перехватывать исключение.

Что же можно еще делать со словарями? Да то же самое, что и с другими объектами: встроенные функции, ключевые слова (например, циклы for и while), а также специальные методы словарей.

Методы словарей

dict.clear() — очищает словарь.

dict.copy() — возвращает копию словаря.

classmethod dict.fromkeys(seq[, value]) — создает словарь с ключами из seq и значением value (по умолчанию None).

dict.get(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None).

dict.items() — возвращает пары (ключ, значение).

dict.keys() — возвращает ключи в словаре.

dict.pop(key[, default]) — удаляет ключ и возвращает значение. Если ключа нет, возвращает default (по умолчанию бросает исключение).

dict.popitem() — удаляет и возвращает пару (ключ, значение). Если словарь пуст, бросает исключение KeyError. Помните, что словари неупорядочены.

dict.setdefault(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а создает ключ со значением default (по умолчанию None).

dict.update([other]) — обновляет словарь, добавляя пары (ключ, значение) из other. Существующие ключи перезаписываются. Возвращает None (не новый словарь!).

dict.values() — возвращает значения в словаре.

Для вставки кода на Python в комментарий заключайте его в теги

Источник

Оцените статью