1. What is a Python dictionary
- A Python dictionary is a built-in data structure that stores a collection of key-value pairs. It is an unordered collection, meaning that the elements in a dictionary are not stored in any particular order. Instead, each element is accessed and retrieved by its associated key.
- Dictionaries are incredibly versatile and commonly used in Python programming due to their efficiency in searching and retrieving values. The keys in a dictionary must be unique and immutable objects, such as strings, numbers, or tuples. On the other hand, the values can be of any data type and can be mutable.
- One of the main advantages of dictionaries is their ability to provide fast lookups. Rather than iterating over the elements to find a specific value, dictionaries use a hashing mechanism to directly map keys to their corresponding values. This makes dictionary lookups very efficient, even for large collections of data.
- Dictionaries can be created using curly braces ({}) or by using the built-in dict() function. Key-value pairs are separated by colons (:), and multiple pairs are separated by commas. Once a dictionary is created, elements can be accessed, added, modified, or removed using various methods and operations.
- Python dictionaries also offer several useful methods for manipulating and retrieving data. For example, the keys() method returns a list of all the keys in the dictionary, while the values() method returns a list of all the values. The items() method returns a list of tuples containing the key-value pairs.
- Dictionaries can be iterated over using loops, providing access to each key or value in the collection. Additionally, Python provides convenient ways to check for the existence of a key in a dictionary and to retrieve a default value if the key is not present.
- Due to their flexibility and efficient lookup capabilities, dictionaries are commonly used for tasks such as storing and retrieving configurations, building data mappings, counting occurrences of elements, and much more. They are a powerful tool in the Python language that enables efficient data manipulation and organization.
Syntax
1 |
dic = {key1: value1, key2: value2, key3: value3, ...} |
To access a value from the dictionary, simply use the name of the dictionary followed by the corresponding key in square brackets:
Example
1 2 |
dic = {key1: value1, key2: value2, key3: value3, ...} print (dic [key1]) # output : value1 |
Example: phone book
1 2 |
phoneBook = {"Elysa": "333678765", "Robert": "4544333456", "Andres": "333245511", "Walid": "333445566"} print(phoneBook ["Robert"]) # output: "4544333456" |
2. Browse the values and keys of a Python dictionary
A Python dictionary has a method called values() that allows you to browse its values, and another named keys() to browse its keys.
Example: print values from a dictionary
1 2 3 4 5 6 7 8 9 |
phoneBook = { "Alberto": "3336633558", "Jean": "3337958414", "Bachlar": "3339584758"} for value in phoneBook.values(): print(value) """ output: 3336633558 3337958414 3339584758 """ |
Example: browse dictionary keys
1 2 3 4 5 6 7 8 9 |
phoneBook = { "Farid": "3336633558", "Najib": "3337958414", "Bernardo": "3339584758"} for key in phoneBook.keys (): print(key) """ output: Farid Najib Bernardo """ |
Note
You can also browse keys and values at the same time by using the items() method
Example: browsing through keys and values
1 2 3 4 5 6 7 8 9 |
phoneBook = { "Majid": "0556633558", "Tomas": "0587958414", "Bernard": "0669584758"} for key, value in phoneBook.items (): print (key, value) """ output: Majid 0556633558 Tomas 0587958414 Bernard 0669584758 """ |
3. Update Python dictionary: add or delete elements
3.1 Update a dictionary element
You can update a dictionary item directly by assigning a value to a key:
Example: Stock Manager
1 2 3 4 5 |
stock = {"USB_Key": 29, "Printer": 45, "Routers": 13 , "Laptops": 31} #modification of the "printer key value stock [ "Printer"] = 22 print (stock) # output: {"USB_Key": 29, "Printer": 22, "Routers": 13 , "Laptops": 31} |
3.2 Add an element to the dictionary
In the case of a non-existent key, the same method mentioned above, allows to add elements to the dictionary:
Example: Add an item to the stock
1 2 3 4 5 |
stock = {"Laptop": 15, "Printer": 35, "Tablet": 27} # Added the "Ipad" element: 21 stock [ "Ipad"] = 21 print (stock) # output: {'Laptop': 15, 'Printer': 35, 'Tablet': 27, 'Ipad': 21} |
3.3 Delete an element from the dictionary
You can remove an element from the dictionary by specifying its key in the pop() method
Example: deleting a dictionary element
1 2 3 4 5 |
stock = {'Laptop': 15, 'Printer': 35, 'Tablet': 27, 'Ipad': 22} # Delete the "Printer" element: 35 stock.pop ( "Printer") print (stock) # output: {'Laptop': 15, 'Tablet': 27, 'Ipad': 22} |
Note
A dictionary has another method: popitem() that removes the last element
Example: Deleting the last item
1 2 3 4 5 |
stock = {'Laptop': 15, 'Printer': 35, 'Tablet': 27, 'Ipad': 22} # Deleting the last element stock.popitem () print (stock) # displays: {'Laptop': 15, 'Printer': 35, 'Tablet': 27} |
3.4 Emptying a dictionary
A Python dictionary can be empty using the clear() method
Example: empty a dictionary
1 2 3 4 5 |
stock = {'Laptop': 15, 'Printer': 35, 'Tablet': 27, 'Ipad': 22} # empty the dictionary stock.clear () print (stock) # displays an empty dictionary: {} |
4. Associated methods with a Python dictionary
Here is a summary of the main methods associated with a dictionary object:
- clear(): removes all items from the dictionary.
- copy(): returns a shallow copy of the dictionary.
- fromkeys (seq [, v]): Returns a new dictionary with the keys of seq and a value equal to v (the default is None).
- get(key [, d]): returns the value of key. If the key does not exit, returns d (the default is None).
- items(): returns a new view of dictionary items (key, value).
- keys(): Returns a new view of the dictionary keys.
- pop(key [, d]): removes the element with key and returns its value or d if key is not found. If d is not provided and the key can not be found, raises KeyError.
- popitem(): delete and return an arbitrary element (key, value). Lift KeyError if the dictionary is empty.
- setdefault(key [, d]): if key is in the dictionary, return its value. Otherwise, insert the key with the value d and return d (the default is None).
- update([other]): Update the dictionary with the key / value pairs of other existing keys.
- values(): returns a new view of dictionary values
Younes Derfoufi
CRMEF OUJDA