1. Define a dictionary in Python

  • Dictionaries in python are unordered collections of objects that is made up of elements and each element consists of a key:value pair.
  • In other programming languages, we talk about associative arrays or hashes.
  • Like lists, dictionaries are mutable and dynamic objects. They can be modified and extended according to your needs.
  • A dictionary can contain objects of any type and even include other dictionaries.
  • It is thanks to these characteristics that dictionaries are often used to create complex data structures where several elements are nested inside each other!
  • A dictionary can be defined by enclosing braces {} with a list of key-value pairs separated by commas.

Syntax

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

dic = {key1: value1, key2: value2, key3: value3, ...}
print (dic [key1]) # output : value1

Example: phone book

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

phoneBook = { "Alberto": "3336633558", "Jean": "3337958414", "Bachlar": "3339584758"}
for value in phoneBook.values():
    print(value)
"""
output:
3336633558
3337958414
3339584758
"""

Example: browse dictionary keys

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

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

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

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

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

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

stock = {'Laptop': 15, 'Printer': 35, 'Tablet': 27, 'Ipad': 22}
# empty the dictionary
stock.clear ()
print (stock)
# displays an empty dictionary: {}

4. Summary of dictionary associated methods

Here is a summary of the main methods associated with a dictionary object:

  1. clear(): removes all items from the dictionary.
  2. copy(): returns a shallow copy of the dictionary.
  3. fromkeys (seq [, v]): Returns a new dictionary with the keys of seq and a value equal to v (the default is None).
  4. get(key [, d]): returns the value of key. If the key does not exit, returns d (the default is None).
  5. items(): returns a new view of dictionary items (key, value).
  6. keys(): Returns a new view of the dictionary keys.
  7. 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.
  8. popitem(): delete and return an arbitrary element (key, value). Lift KeyError if the dictionary is empty.
  9. 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).
  10. update([other]): Update the dictionary with the key / value pairs of other existing keys.
  11. values(): returns a new view of dictionary values

 

Younes Derfoufi
my-courses.net

Leave a Reply