Info4 Chap7
Info4 Chap7
Dictionaries
2024/2025
C.SAYAH
Definition and creation of a dictionary
What’s a dictionary?
• A dictionary is a collection of key-value pairs, where each key is unique, and it maps
to a specific value.
• Dictionaries are ordered and changeable, and don’t allow duplicate keys.
How to create a dictionary?
• To create a dictionary, use curly braces {}
• Each key is separated from its value using a colon :
• Key-value pairs are separated by commas ,
1
Definition and creation of a dictionary
• To avoid errors if the key doesn’t exist, use the method get().
2
Removing dictionary items
❑ Use the function pop(key) to remove a key and returns its value.
❑ Use the function popitem() to remove and returns the last key-value pair.
❑ Use the function clear() to empty the dictionary : it returns an empty dict {}.
3
Traversing dictionary items
• You can loop through a dictionary by using a for loop, and there are three traversing methods
➢ Loop through keys
4
Dictionaries as function parameters
5
Dictionaries as function parameters
6
Exercise
8
Thank you!
Do you have questions?