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()

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *