.get in Python 3

Asked

Viewed 1,430 times

4

Hello. I’m starting in python, and saw the following tutorial:

phone_num = input("Numero De Telefone: ")


Mapa_De_Digitos = {
    "1": "Um",
    "2": "Dois",
    "3": "Três",
    "4": "Quatro"
}
output = ""
for ch in phone_num:
    output += Mapa_De_Digitos.get(ch, "") + " "
print(output)

My Doubt is: I don’t understand this ". get" , I’ve never seen it in any pdf book here. I’m not getting this code.

I don’t know if this kind of explanation is allowed here in this community, but I would very much like a very simple explanation for laypeople to understand.

  • I think I just got it. Correct me if I’m wrong: # If "ch" from IMPUT equals the Mapa_de_digits List Key -> The "get" #...method shows the corresponding value (Value key) of the list item.

  • Your "for" loop will scan all digits of your input, one by one, into the variable "ch" and will test if it matches any key in your dictionary "Mapa_de_digitos", if it matches, it will print the value in full and if there is no key equal to "ch"will print an empty string.

2 answers

5

The get() is a method used to take the value of a given key in a dictionary if the key is in the dictionary, if it does not exist, the method returns None or the default value passed by parameter.

The get() can be used, for example, in this way:

dicionario = {'A': 1, 'B': 2} 
valor = dicionario.get('A')
print(valor)
# Imprime '1' na tela

In the above example, we use only one parameter, but the get() accepts two parameters:

  • The key to be searched in the dictionary;
  • The value to be returned if the key is not found (optional).

Using the same example, now using the second parameter to return a default value when the fetched key does not exist:

dicionario = {'A': 1, 'B': 2} 
valor = dicionario.get('C', 'Não encontrado!')
print(valor)
# Imprime 'Não encontrado!' na tela

In his example, the method get() is inside a loop for and this loop is done in each character of the string provided by the user in the first line.

For example if I provide '123' as input, ch will iterate in '1', '2' and '3' and the execution of Mapa_De_Digitos.get(ch, "") will return the value relative to key ch in each iteration of your loop: 'Um', 'Dois' and 'Três'.

If it were the case that a key does not exist in your dictionary, an empty string '' would be returned.

1

In this example,Mapa_De_Digitos is a dictionary type objetto, to see the type of an object use, type():

type(Mapa_De_Digitos)
Out[7]: dict

In case the get() is one of the methods of the class that defines the dictionary object, to see the methods available in an object use dir(objeto), I won’t play below because the list is immense, but you can prove that get() is in the list of methods like this:

'get' in dir(Mapa_De_Digitos)
Out[9]: True

Definition of dicionário:
A Python dictionary is a data structure that, unlike sequences that are indexed by a crease of numbers, dictionaries are indexed by keys (Keys), that are imútavies types, strings and numbers can represent these keys, according to the own documentation, the best way to think of a dictionary and as a set of key pairs:value (key:value). with the restriction that keys have to be unique (within a dictionary), an empty dictionary is defined by a key pair (braces)

The method get():
The method recovers the value assigned to the key Voce sends as argument to the method, but also Voce can do this with format dict[key], see below:

Mapa_De_Digitos.get("4")
Out[14]: 'Quatro'

Mapa_De_Digitos["4"]
Out[15]: 'Quatro'

The advantage of the method get() is that it always returns something, if the key does not exist, the value None is returned, while in parentheses format an error exception is raised when the key does not exist, see:

nine = Mapa_De_Digitos.get(9)
print(nine)
None

nine = Mapa_De_Digitos[9]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-bb87d7f1428a> in <module>()
----> 1 nine = Mapa_De_Digitos[9]

KeyError: 9

Browser other questions tagged

You are not signed in. Login or sign up in order to post.