Python get dictionary

Python get dictionary

In this lesson we will study a Python method, get(), for use on a dictionary.

The Python get() method returns the value of the specified key, if it exists in the dictionary. If the key does not exist it will return None (if get () is used with only one argument).

The syntax is as follows:

d.get(key, value)

Where is it:

key – represents the name of the key of the element from which we want to return the value.

value – optional, is the value to return if the key is not found. By default it is None.

Example of using Python get dictionary

Let’s see a very simple example of use. Suppose we have the following dictionary:


student = {'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'}

Then we use the get method on this dictionary to print the student’s name.


print(student.get('name'))

Now let’s try to print a key that doesn’t exist:


print(student.get('surname'))

If you try the code in the online compiler that you find at the following link: compiler online Python you can see that None will be returned.

Potremmo stampare un messaggio differente, come nel seguente esempio:


print(student.get('surname', 'The surname was not found'))

Using the Python get method nested in dictionary

Let’s now take another example of using the get method on dictionaries in Python. In this example we will use a dictionary where the key is numeric while the value is represented by another dictionary.

We select the name of only one student.


students = {'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}}

student = student.get('1', {}).get('name')
print(student)

Now we print all the student names with a loop, always using the get () method we just studied:


students = {'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}}

for student in students.values():
  print(student.get('name'))

What if we want to print everything?
We could use 2 for loops, as in the example below:


''' 
Python get dictionary
use of the double for loop
'''
students = {'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}}

for student_id, student_detail in students.items():
    print("\nStudent Key:", student_id)
    
    for key in student_detail:
        print(key + ':', student_detail[key])

Try these solutions in the online compiler that you will find at this link: online python compiler. The link will open on a new page so you can write the code.

Conclusion

In this lesson we studied Python get() method and saw how it can be applied to our dictionary exercises. In the next lessons there will be many other examples of use of this method and many others.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Create dictionary in Python

Create dictionary in Python

In this lesson I propose a series of exercises on how to create a dictionary in Python, to learn new concepts.

Create dictionary in Python – first exercise

The first exercise I propose allows you to take lists and process them in order to create a list of dictionaries.

Create three lists representing names, surnames and ages. For example names: Tom, Mario, Luisa; surnames: Rossi, Verdi, Gialli; age: 22, 23, 21. Then create a new list where each element is represented as {‘name’: name, ‘surname’: surname, ‘age’: age}. The elements must be coupled according to the order.

Here is a possible solution to the proposed algorithm that makes use of zip, an object that is an iterator of tuples and couples each iterated element:


names = ['Tom','Mario','Luisa']
surnames = ['Rossi', 'Verdi', 'Gialli']
ages = [22,21,23]

contacts = []

for name, surname, age in zip(names,surnames,ages):
  contacts.append({'nome': name, 'cognome': surname, 'age': age})
  
print(contacts)

Create dictionary in Python – second exercise

Here is another exercise that allows you to practice with dictionaries.

Create a source dictionary that contains a first and last name. Then enter the matriculation, asking for it as input and then add the exams taken with the name of the subject and the grade obtained.

To solve the algorithm I first created a dictionary with the name and surname of a student. I then asked the student to enter his or her registration number. Then I asked how many subjects he or she wants to add and for each subject we added the name and the grade.

Here, then, is a possible solution:


contacts = {'name':'Tom','surname':'Verdi'}

contacts['matriculation'] = input('Enter the student\'s matriculation number: ')
contacts['exams'] = []

n = int(input('How many subjects do you want to add?'))

for i in range(1, n + 1):
  matter = input('Enter the matter:')
  grade = int(input('Enter your grade:'))
  contacts['exams'] +=  [{'matter': matter,'grade': grade}]

print(contacts)

Conclusion

Of course these are just some exercises on how to create a dictionary in Python, look for other alternative solutions.

In later lessons I will talk more about dictionaries and the methods to use on them.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Python List Sort

Bubble sort

Python max()