Python dictionary get() Method
Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.
Syntax
Following is the syntax for get() method −
Parameters
key − This is the Key to be searched in the dictionary.
default − This is the Value to be returned in case key does not exist.
Return Value
This method return a value for the given key. If key is not available, then returns default value None.
Питонисты, прекратите использовать квадратные скобки для получения значений из словаря
Привет, Хабр! представляю вашему вниманию перевод статьи «Stop Using Square Bracket Notation to Get a Dictionary’s Value in Python» автора Jonathan Hsu.
Выходим за рамки традиционного метода и защищаем свой код
Словарь — это несортированный набор ключей и значений. Это значит, что:
- Каждый элемент словаря состоит из термина (ключ) и его определения (значение).
- Ключи должны быть уникальными для данного словаря — никаких повторений.
- Ключи в словаре не имеют такого явного порядка расположения, который есть у элементов списка.
Традиционный (и небезопасный) способ получения значения из словаря.
При обычном доступе к значению элемента из словаря используются квадратные скобки. При использовании такой записи после имени словаря в квадратных скобках указывается ключ:
Обратите внимание, что попытка обратиться к значению по ключу, которого нет в словаре, вызовет исключение KeyError. Это может создать серьёзные проблемы, особенно при работе с непредсказуемыми рабочими данными.
Конечно, можно воспользоваться конструкцией try/except или использовать инструкцию if. Но такое повышенное внимание к столь простой операции лишь загромождает код.
Если у вас за плечами опыт разработки на JavaScript, то вам, возможно, захочется получить значение из словаря с помощью точечной нотации. Но в Python’е это не сработает.
Используем метод get()
Когда вам нужно получить значение из словаря, то самым безопасным способом будет использование метода get(). У этого метода есть два параметра:
- Первый (обязателен): имя ключа, по которому мы хотим получить значение. Это имя может быть строкой или может быть именем переменной, если наш ключ может меняться по ходу программы.
- Второй (не обязателен): значение, которое будет использовано, если нашего ключа в словаре вдруг не окажется.
Если ключ существует в словаре, то метод get() работает точно таким же образом, как и обращение по ключу в квадратных скобках. Зато в случае, когда такого ключа в словаре нет, метод get() вернёт значение по умолчанию, избавив вас от необходимости обрабатывать исключение.
Значением по умолчанию может быть любой допустимый в данном контексте объект. Не забывайте о том, что этот параметр не обязателен. Поэтому, если вы его не укажете явным образом, то при попытке обратиться по несуществующему в словаре ключу, метод get() вернёт объект None.
Используем метод setdefault()
Иногда вам будет нужно не только безопасно получить данные из словаря, но и также безопасно добавить новые данные в словарь. Для этого у словарей есть метод setdefault(). Он имеет те же параметры, что и метод get(), но в отличие от последнего, при обращении к словарю по несуществующему ключу, он не только вернёт переданное по умолчанию значение, но и создаст в словаре новый элемент с этим ключом и переданным значением. Если при обращении к словарю с помощью метода setdefault() передаваемый ключ уже есть в словаре, то данный метод оставит словарь без изменений.
print(author.setdefault(‘username’)) # выведет Friday1719
print(author.setdefault(‘middle_initial’, “Monday”)) # выведет Monday и создаст
# в словаре элемент с ключом ‘middle_initial’ и значением для этого ключа “Monday”
В примере выше мы видим, что поведение метода setdefault() ничем не отличается от поведения метода get() или от применения квадратных скобок при обращении к словарю по существующему в нём ключу. В случае, если такого ключа в словаре нет, то метод setdefault() не только вернёт в программу значение своего второго аргумента (как и метод get()), но и создаст в словаре элемент с переданными ему ключом и значением. Это поведение метода setdefault() и отличает его от метода get().
Теперь, если выполнить пример выше и вывести элементы словаря, то мы получим такой результат:
Применение методов get() и setdefault() является первоклассной техникой при обращении к значениям словаря. Нужно лишь время, чтобы отказаться от старых привычек и начать использовать эту технику на практике.
Если вам нужно только получить значение из словаря, то ваш помощник — метод get().
Если же вам нужно безопасно добавить новое значение в словарь, то вызывайте метод setdefault().
Python Dictionary get()
In this tutorial, we will learn about the Python Dictionary get() method with the help of examples.
The get() method returns the value for the specified key if the key is in the dictionary.
Example
Syntax of Dictionary get()
The syntax of get() is:
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()
get() method returns:
- 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?
Output
Python get() method Vs dict[key] to Access Elements
get() method returns a default value if the key is missing.
However, if the key is not found when you use dict[key] , KeyError exception is raised.
Python requests: GET Request Explained

In this tutorial, you’ll learn how to use the Python requests library’s get method to fetch data via HTTP. The Python requests library abstracts the complexities in making HTTP requests. The requests.get() method allows you to fetch an HTTP response and analyze it in different ways.
By the end of this tutorial, you’ll have learned:
- How the Python requests get method works
- How to customize the Python requests get method with headers
- How to use the Python response objects
Table of Contents
Understanding the Python requests get Function
An HTTP GET request is used to retrieve data from the specified resource, such as a website. When using the Python requests library, you can use the .get() function to create a GET request for a specified resource.
The function accepts a number of different parameters. Let’s take a look at the function and the different parameters that it accepts:
We can see in the code block above, that the function accepts two parameters:
- A url , which points to a resource, and
- params , which accepts a dictionary or tuples to send in the query string
The .get() function is actually a convenience function based off of the .request() function. The optional keyword arguments that you can pass in derive from that function. Let’s take a look at the options that you can pass in:
| Parameter | Description | Default Value |
|---|---|---|
| allow_redirects | Whether or not to allow redirection | True |
| auth | A tuple to enable secure HTTP authentication | None |
| cert | A string or tuple specifying the certification file or key | None |
| cookies | A dictionary of cookies to send to the specified URL | None |
| headers | A dictionary of HTTP headers to send | None |
| proxies | A dictionary of the protocol of the proxy URL | None |
| stream | A boolean indicator to determine if the response should be downloaded (when set to False ) or streamed (when set to True ) | False |
| timeout | A number or tuple indicating how many seconds to wait for a client to make a connection or send a response. The default value of None means that the request will wait indefinitely. | None |
| verify | A boolean or string indication to test the server’s TLS certificate | True |
The optional keyword arguments available in the requests.get() function
Now that you have a strong understanding of the Python requests.get() function, let’s take a look at how you can make a GET request.
Making a Python requests GET Request
In this section, you’ll learn how to use the requests.get() function to make a GET request. For this tutorial, we’ll use a mock API that allows you to emulate a real-world scenario. For this, we’ll query the /users endpoint of the URL, by accessing the URL https://reqres.in/api/users .
Let’s see how we can use the get() function to make a GET request:
Let’s break down what we did in the code above:
- We imported the requests library
- We created a new variable, resp , which is the result of passing our endpoint into the get() function
- We then printed out the variable, which returned a Response object
In the following section, you’ll learn how to make use of this Response object to retrieve response information.
Understanding the Python requests response Object
In the previous section, you learned how to create a Response object. The Response object has a number of different properties and methods that we can access to learn more about the data that has been returned.
Some of the key properties and methods available to a Response object include:
- .status_code , which is the integer code of the responded HTTP status, such as 200 or 404
- .ok , which return True is the status code of the response is less than 400, otherwise False
- .json() , which returns the JSON-encoded content of a response
- .content , which contains the content of the response
- .next , which returns a request for the new request in a redirect chain, if there is one
Let’s see how we can use some of these properties and methods to understand the response we get back from our API call:
In the code block above, we checked what the .status_code of the Response object was. Since it was in the 200s, we can be confident that an acceptable request was made.
Let’s take a look at how we can understand the data that has been returned:
In the code above, we converted our Response object to a Python dictionary, by applying the .json() method to our object. Because of this, we can now access items in the response by using their key:
In the next section, you’ll learn how to pass headers into a Python GET request.
Passing Headers into a Python requests get Method
In many cases, when accessing APIs or other web data, you’ll need to provide some form of authentication. This can be done by passing in information via headers . Headers can also be used to pass in other forms of information, such as the content type you’d like returned.
Let’s see how we can pass in a mock API key into our query:
Let’s break down what the code above does:
- We create a dictionary of headers, headers , that contains key-value pairs of information to pass into our request.
- We use the headers= parameter to pass in our dictionary into our request.
The types of headers that will be accepted will vary depending on the web resource that you’re accessing.
In the following section, you’ll learn how to use query string parameters in a Python requests get() function.
Using Query String Parameters in a Python requests get Method
Query string parameters allow you to customize a GET request by passing values directly into the URL or into the params= parameter.
Before diving further, you may be wondering why you’d want to do this. Take a look at the data that has been returned by our previous API call. The data indicates that six records were returned. It also indicates that the first of two pages was returned. So, how do we access the second page?
The answer to this, as you may have guessed, is to use query parameters. In order to access the second page of our data, we can pass in that we want to access page #2. There are three ways to accomplish this:
- Pass in a dictionary of parameters into the params= parameter, such as
- Pass in a list of tuples into the params= parameter, such as [(‘page’, ‘2’)]
- Directly modify the URL string by appending ?page=2 to the URL
Let’s see how we can use the first method to accomplish this:
We can see that by passing in our query parameters our query returned the second page.
Conclusion
In this tutorial, you learned how to make GET requests using the Python library, requests . You first learned how the get() function works, including how to access additional parameters via keyword arguments.
Then, you learned how to use the get() function to make a request and how to access properties and use methods of the returned Response object. Finally, you learned how to apply headers and query parameters to your GET request.