Dictionaries and Functions¶

Karën Fort (CC BY-NC-SA) -- 2024

This notebook corresponds to your fourth lecture and covers :

  • Dictionaries
  • functions

It is inspired from different sources:

  • Loic Grobol's material
  • Gaël Guibon's slides and lab material from Master TAL (Univ. de Lorraine)
  • W3School tutorial

Dictionaries¶

Dictionaries are data structures where you can store for each entry a key and a value. The value can be accessed using the key:

In [9]:
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

In [19]:
#TODO Code me!

Modifying a dictionary¶

Dictionaries are mutable: it is possible to add and remove items in a Dictionary

In [12]:
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)

In [14]:
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):

In [15]:
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)

In [10]:
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!

In [18]:
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

In [20]:
# 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?

In [21]:
import sys

print(sys.version)
3.6.9 (default, Mar 10 2023, 16:46:00) 
[GCC 8.4.0]

Looping through Dictionaries¶

Note that we loop on the keys of the dictionary!

In [2]:
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
In [3]:
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
In [45]:
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

Functions¶

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?

In [71]:
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...

In [74]:
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):

In [76]:
def HelloWorld():            # function definition (note the :)
    print("Hello, World!")
    
HelloWorld()                # function call
Hello, World!
In [78]:
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:

In [85]:
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:

In [86]:
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")
Out[86]:
'Unknown language'

A function can take several parameters:

In [4]:
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)
Out[4]:
'Bonjour Karen'

Arguments can be of more complex types, like lists:

In [6]:
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:

  • 3
  • 0
  • titi
In [7]:
#TODO Code me!

Going further¶

  • Recursion: Check the W3School doc (Recursion)