Karën Fort (CC BY-NC-SA) -- 2024
Dictionaries
are data structures where you can store for each entry a key
and a value
. The value
can be accessed using the key
:
my_dico ={
"name": "Shelly-Ann Fraser-Pryce",
"country": "Jamaica",
"nb_olympic_medals": 8
}
print(my_dico)
print(my_dico.get("country"))
print(my_dico.keys())
print(my_dico.values())
{'name': 'Shelly-Ann Fraser-Pryce', 'country': 'Jamaica', 'nb_olympic_medals': 8} Jamaica dict_keys(['name', 'country', 'nb_olympic_medals']) dict_values(['Shelly-Ann Fraser-Pryce', 'Jamaica', 8])
🥳 print the size of the dictionary
#TODO Code me!
Dictionaries
are mutable: it is possible to add and remove items in a Dictionary
k = my_dico.keys()
print(k) #before the change
my_dico["gender"] = "female"
print(k) #after the change
my_dico.pop("gender")
print(k) #after the removal
dict_keys(['name', 'country', 'nb_olympic_medals']) dict_keys(['name', 'country', 'nb_olympic_medals', 'gender']) dict_keys(['name', 'country', 'nb_olympic_medals'])
A Dictionary
can be completely removed, using del
(with the weird syntax)
del my_dico
print(my_dico)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-14-1f57f8b2e982> in <module> ----> 1 del my_dico 2 print(my_dico) NameError: name 'my_dico' is not defined
A Dictionary
can be emptied (but it still exists):
my_dico2 ={
"name": "Shelly-Ann Fraser-Pryce",
"country": "Jamaica",
"country": "USA",
"nb_olympic_medals": 8
}
my_dico2.clear()
print(my_dico2)
{}
Dictionaries
do not allow duplicates (duplicate values will overwrite existing values)
my_dico2 ={
"name": "Shelly-Ann Fraser-Pryce",
"country": "Jamaica",
"country": "USA",
"nb_olympic_medals": 8
}
print(my_dico2)
{'name': 'Shelly-Ann Fraser-Pryce', 'country': 'USA', 'nb_olympic_medals': 8}
A Dictionary
can store any values, including collections!
my_dico2 ={
"name": "Shelly-Ann Fraser-Pryce",
"country": "Jamaica",
"country": "USA",
"nb_olympic_medals": [3,4,1] # nb of gold, silver and bronze medals resp.
}
print(my_dico2)
{'name': 'Shelly-Ann Fraser-Pryce', 'country': 'USA', 'nb_olympic_medals': [3, 4, 1]}
🥳 adapt the previous dictionary
to be used in you Olympics TD
# TODO Code me!
Ordered or not?
In Python 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Which version of Python do you have?
import sys
print(sys.version)
3.6.9 (default, Mar 10 2023, 16:46:00) [GCC 8.4.0]
Note that we loop on the keys
of the dictionary!
dict1 = {
"name": "Shelly-Ann Fraser-Pryce",
"country": "Jamaica",
"country": "USA",
"nb_olympic_medals": 8
}
print("These are the keys of dict1: ")
for k in dict1: # k is a key in the dico
print(k)
These are the keys of dict1: name country nb_olympic_medals
print("These are the values of dict1: ")
for k in dict1: # k is a key in the dico
print(dict1[k])
These are the values of dict1: Shelly-Ann Fraser-Pryce USA 8
print("These are the items of dict1: ")
for x, y in dict1.items(): # x, y are key,value in the dico
print(x, y)
These are the items of dict1: name Shelly-Ann Fraser-Pryce country USA nb_olympic_medals 8
Let's discover the Turtle
, a Python implementation of the Logo Turtle), that allows to draw using simple methods (doc).
What does the following code do?
from turtle import *
t = Turtle()
t.shape("turtle")
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
mainloop()
Nice! But boring to write... the same goes for your code concerning the athletes...
We need a way to store certain actions, so that we can reuse them without having to copy/paste them all the time...
from turtle import *
t = Turtle()
t.shape("turtle")
def forwardLeft(tutu):
tutu.forward(100)
tutu.left(90)
forwardLeft(t)
forwardLeft(t)
forwardLeft(t)
forwardLeft(t)
mainloop()
Back to basics (Turtle
does not work so well on Jupyter):
def HelloWorld(): # function definition (note the :)
print("Hello, World!")
HelloWorld() # function call
Hello, World!
def compute(): # you can add any number of instructions in your function
a_number = 2713
print(2*a_number)
compute()
5426
We can add parameters
to a function:
def hello(lang): # here lang is a parameter
if lang == "fr":
print("Bonjour")
elif lang == "bzg":
print("Demat")
else:
print("Unknown language")
print("I'm done")
hello("fr") # here "fr" is an argument (the value of the parameter)
hello("en")
Bonjour I'm done Unknown language I'm done
Note the difference between print()
and return
:
def hello(lang): # here lang is a parameter
if lang == "fr":
return("Bonjour")
elif lang == "bzg":
return("Demat")
else:
return("Unknown language")
print("I'm done")
hello("fr") # here "fr" is an argument (the value of the parameter)
hello("en")
'Unknown language'
A function
can take several parameters:
def hello_you(your_name,lang): # here lang is a parameter
if lang == "fr":
return("Bonjour "+your_name)
elif lang == "bzg":
return("Demat "+your_name)
else:
return("Unknown language")
print("I'm done "+your_name)
hello_you("Karen","fr") # here "fr" is an argument (the value of the parameter)
'Bonjour Karen'
Arguments can be of more complex types, like lists
:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
apple banana cherry
🥳 write a function "square" that returns the square of the (supposedly) number passed as argument.
Test it with the following arguments:
#TODO Code me!