Dictionaries in Python
The Python dictionary is a collection of unordered items. While other types of compound data have value only as an element, a dictionary has a pair key:value.
A Python dictionary works similarly to a dictionary in a real world. The keys in a dictionary must be unique and of immutable data type, such as strings, integers, and tuples, but the key-values can be repeated and be of any type.
Each key corresponds to a value, so we cannot have duplicate keys. Dictionaries are editable objects, which means that we can add, delete, or update items after they are created.
Dictionaries are optimized to retrieve values when the key is known.
Create a dictionary
Creating a dictionary is as simple as placing items in braces {}, separated by commas.
Example 1 :
# empty dictionary dict1={} print("dict1 : ",dict1) # dictionary with string keys dict2={"Prenom":"Mostafa", "age":20,"ville":"Meknes"} print("dict2 : ",dict2) # dictionnaire avec des clés entières dict3= {1:"Meknes", 2:"Marrakech", 3:"Essaouira"} print("dict3 : ",dict3) # dictionary with mixted keys dict4={1:"Mostafa", "ville":"Meknes", 10.4: 1.78} print("dict4 : ",dict4) # Création d'un dictionnaire avec la méthode dict () dict5 = dict({1: 'Dev', 2: 'Info', 3:'COM'}) print("dict5 : ",dict5) # Create a dictionary with each element in pair dict6 = dict([(1, 'Dev'), (2, 'Info')]) print("dict6 : ",dict6)
dict2 : {'Prenom': 'Mostafa', 'age': 20, 'ville': 'Meknes'}
dict3 : {1: 'Meknes', 2: 'Marrakech', 3: 'Essaouira'}
dict4 : {1: 'Mostafa', 'ville': 'Meknes', 10.4: 1.78}
dict5 : {1: 'Dev', 2: 'Info', 3: 'COM'}
dict6 : {1: 'Dev', 2: 'Info'}
As you can see above, we can also create a dictionary using the built-in dict() function.
How to access the elements of a dictionary?
As previously mentioned, the order of elements in a dictionary can vary. Therefore, we cannot use the item index to access the value. Instead, we use a key. To access the dictionary value, we use the following syntax:
Syntax :
dict_name[key]
Example 2 :
D={1:"Mostafa", "ville":"Meknes", 10.4: 1.78} print("Key 1 : ", D[1]) print("Key ville ", D["ville"]) print("Key 10.4 : ", D[10.4])
Key ville Meknes
Key 10.4 : 1.78
If the specified key does not exist, a KeyError exception will be raised.
Example 3 :
D={1:"Mostafa", "ville":"Meknes", 10.4: 1.78} print(D[2])
File "prog.py", line 2, in < module>
print(D[2])
KeyError: 2
Adding and modifying elements
Dictionary are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, the value is updated, otherwise a new key: value pair is added to the dictionary.
Example 4 :
D={1:"Mostafa", "ville":"Marrakech", 10.4: 1.78} print(D) # Change the "ville" key D["ville"]="Meknes" print(" D : ", D) # Add a key age D["age"]=32 print(" D : ", D)
D : {1: 'Mostafa', 'ville': 'Meknes', 10.4: 1.78}
D : {1: 'Mostafa', 'ville': 'Meknes', 10.4: 1.78, 'age': 32}
Delete items
We can delete a particular element in a dictionary using the pop() method. This method removes as an element with the key provided and returns the value.
The popitem() method can be used to remove and return an arbitrary item (key, value) from the dictionary. All elements can be deleted at once using the clear() method.
We can also use the del keyword to delete individual items or the entire dictionary itself.
Example 5 :
D={1:"Mostafa", "ville":"Marrakech", 10.4: 1.78, "age":32, 3:45, "tt":"test"} print(D) print("val : ", D.pop(1)) print("pop : ",D) print("val : ", D.popitem()) print("popitem : ",D) del D["age"] print("del : ", D) # Clear the dictionary D.clear() print(D)
val : Mostafa
pop : {'ville': 'Marrakech', 10.4: 1.78, 'age': 32, 3: 45, 'tt': 'test'}
val : ('tt', 'test')
popitem : {'ville': 'Marrakech', 10.4: 1.78, 'age': 32, 3: 45}
del : {'ville': 'Marrakech', 10.4: 1.78, 3: 45}
{}
Dictionary methods
The methods available with dictionary are summarized below. Some of them have already been used in the examples above.
Method | Description |
---|---|
clear() | Remove all items from the dictionary. |
copy() | Return an independent copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with the keys of seq and a value equal to v (the default value is None). |
get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (the default value is None). |
items() | Returns a new view of the elements of the dictionary (key, value). |
keys() | Returns a new view of dictionary keys. |
pop(key[,d]) | Delete the element with "key" and return its value or "d" if "key" cannot be found. If "d" is not supplied and "key" is not found, KeyError is raised. |
popitem() | Remove and return an arbitrary item (key, value). KeyError if the dictionary is empty. |
setdefault(key[,d]) | If "key" is in the dictionary, returns its value. Otherwise, insert "key" with the value "d" and return "d" (the default is None). |
update([dict]) | Update the dictionary with the key / dict value pairs by replacing the existing keys. |
values() | Renvoyer une nouvelle vue des valeurs du dictionnaire |
Example 6 :
D={1:"Mostafa", "ville":"Marrakech", 10.4: 1.78} cles=D.keys() print(cles) print(type(cles))
<class 'dict_keys'>
The keys() method returns a dict_keys type sequence. Treat the dict_keys object as an immutable list that you can use in a for loop or pass it to other functions for further processing. If you want a list or a tuple, simply pass the result of the keys() method to the list() or tuple() constructor as follows:
Example 7 :
D={1:"Mostafa", "ville":"Marrakech", 10.4: 1.78} cles=list(D.keys()) print(cles) print(type(cles))
<class 'list'>
Example 8 :
D={1:"Mostafa", "ville":"Marrakech", 10.4: 1.78} for elem in D.items(): print(elem)
('ville', 'Marrakech')
(10.4, 1.78)
0 Comment(s)