In Python, a dictionary represents a collection of unique key-value pairs. Dictionaries are also called Associative arrays or mappings.
A dictionary gets the name from how it associates a particular key to a particular value, just like how an English dictionary associates a word with a definition.
Dictionaries are represented using the builtin dict()
class. This class defines the behavior and methods for working with dictionaries
Unlike in some other data types such as lists where values are accessed with their indices, in dictionaries, values are accessed with their keys
Empty curly braces are used to initialize an empty dictionary.
We can also use the builtin dict()
function to create an empty dictionary, as in:
Initializing Non-empty dictionaries
When initializing non-empty dictionaries, the comma-separated key:value
pairs are enclosed in curly braces.
The key part and the value part are separated by a colon, while the items themselves are separated by commas.
Example of non-empty dictionaries:
In the above example, we are associating a number with its word.
All keys in a dictionary must be unique, if a key is repeated, it will get associated with the latest value. Actually, the latest value overwrites the older value.
In the above example, the key 4
is repeated twice. As shown by the output, only the latest value("Javascript"
) is retained in the dictionary.
Hashability of dictionary keys
While any object can be used as a value in a dictionary item, not every object can be used as a dictionary key. For an object to be eligible for use as a key, it must be hashable.
Typically, all immutable values such as integers, floats, strings and tuples are hashable, while mutable objects such as lists , sets and dictionaries are non-hashable. Therefore, we can only use immutable objects as dictionary keys.
Trying to use a non-hashable object as a key will raise a TypeError
.
Check whether an object is a dictionary
Dictionaries in Python are represented using the built-in dict
type.
We can use the isinstance()
function with dict
as the second parameter to check explicitly whether a given object is a dictionary:
Operations on Dictionaries
Dictionaries are unordered, and their keys are unique. This means that some common operations, such as concatenation, repetition, indexing, and slicing, are not applicable to dictionaries. These operations assume an order on the items, which dictionaries do not have. Additionally, repetition on dictionaries would violate the uniqueness of keys property, which ensures that each key in a dictionary maps to a unique value.
However, other operations including some which are unique to dictionaries can be performed. These operations are discussed below.
Accessing the value associated with a key
We use square brackets with key as the parameter, to access an element in the dictionary. The syntax is as follows:
D[key]
The value associated with the given key is returned.
This is called dictionary lookup because just like looking up a word in a dictionary, you are searching for the corresponding value that is associated with a specific key.
Since elements in a dictionary are unordered, we cannot use indexing to access items. If we try accessing elements with their index such as D[index], Python will try associating the given index with a key in the dictionary, if no such key exists, a KeyError
will be raised.
The get()
method can be used to get the value associated with a given key without raising a KeyError
if the given key is not in the dictionary. Additionally, this method takes an optional argument which gets returned as the default value if the given key is not found. Its syntax is as follows:
D.get(k, d)
The value associated with key k will be returned, Otherwise the default value , d, will be returned. d is optional and if it is not given, it will default to None.
Looping on Dictionaries
Dictionaries are iterable, this means that we can use the for loop to access items in the dictionaries. However, using the for loop with the in
operator only returns the keys.
We can use dictionary lookup, to access the value associated with the given key during each iteration.
The dict
class has three important methods which can be used to access keys and values in dictionary instances.
The keys()
method returns an object containing all the keys in the dictionary:
We can use the keys()
method to loop through the dictionary keys, as shown below;
The values()
methods, returns an object containing all the values in a dictionary.
We can use this method to loop through the dictionary values.
The items()
method returns an object containing both key value pairs of each item of the dictionary. Looping on this object returns a tuple containing the key-value pairs.
Adding and Updating Dictionary items
The square brackets can be used to add new items to a dictionary. The syntax is as follows:
D[key] = value
However, if the given key already exists in the dictionary, the existing value will simply get overwritten with the new value.
Therefore, if the key does not exist in the dictionary, a new item will be added , otherwise, an existing item will get updated.
The update()
method
In addition to the d[key] = value
syntax, the dict
class provides the update()
method which can be used to populate a dictionary with multiple elements simultaneously.
In the above example we used the update() method to update a dictionary with elements of another dictionary. However, the update()
method is more flexible than that. In addition to updating a dictionary with elements from a dictionary-like object, It as well allows an iterable of key-value pairs to be used instead. Consider the following example:
Deleting dictionary items
The del
keyword can be used to effectively delete an item from the dictionary. Its syntax is as follows:
del <dictionary>[<key>]
The del
statement raises a KeyError
if the given key does not exist in the dictionary.
Similarly, the pop()
method can also be used to delete an item. The method returns the value that was associated with the deleted item.
The pop()
method also raises a KeyError
if the key does not exist but we can silence the error by providing an optional argument to the method which will get returned as a default value in case the key does not exist.
The popitem()
method is used to delete a random item in the dictionary. It returns a tuple holding the key and the value of the deleted item. The method takes no arguments. its syntax is as follows:
D.popitem()
This method raises a KeyError
if the dictionary is empty.
The clear()
method removes all the items in a dictionary, effectively making it an empty dictionary. its syntax is as follows:
D.clear()