βοΈDictionary
A Python dictionary is an unordered collection of key-value pairs that is mutable, meaning you can change its contents, unlike tuples and strings. It is also known as associative arrays, hash tables, or simply hashes. Each key-value pair in a dictionary is separated by a colon (:), and the pairs are separated from each other by commas. A dictionary is defined within curly braces ({}) and can be assigned to a variable just like any other data type in Python.
Dictionaries are extremely useful when it comes to dealing with large data sets or datasets where the position of data is not important. Instead, what is important is the association between two pieces of information.
In Python, dictionaries are implemented as hash tables, which means that the time complexity for accessing, inserting, or deleting a key-value pair is O(1), making them very efficient for many use cases.
Creating a Dictionary
In Python, we can create a dictionary by enclosing a comma-separated list of key-value pairs inside curly braces {}
. Each key-value pair is separated by a colon :
. Here is an example:
Output:
In the example above, we created a dictionary called person
that contains three key-value pairs: 'name': 'John'
, 'age': 30
, and 'city': 'New York'
. We then printed the dictionary using the print()
function.
Accessing Elements from a Dictionary
We can access the elements of a dictionary by referring to its key name, inside square brackets or by using the get()
method.
Example using square brackets:
Example using the get()
method:
If we try to access a key that does not exist in the dictionary using square brackets, we will get a KeyError
. However, if we use the get()
method and the key does not exist in the dictionary, it will return None
(or a default value we can specify).
Updating and Adding Elements to a Dictionary
To update an element in a dictionary, we can simply access the key and reassign a new value to it. If the key does not exist, it will be added as a new key-value pair.
Here's an example:
In this example, we first created a dictionary my_dict
with three key-value pairs. Then we updated the value of the key 'apple'
to 3
. Finally, we added a new key-value pair 'pear': 5'
to the dictionary.
Removing Elements from a Dictionary
We can remove elements from a dictionary in several ways, using the del
keyword, pop()
method, and clear()
method.
Using the
del
keyword:
We can use the del
keyword to remove a specific key-value pair from the dictionary. Here's an example:
Using the
pop()
method:
We can use the pop()
method to remove a specific key-value pair from the dictionary and return the value of the removed key. Here's an example:
Using the
clear()
method:
We can use the clear()
method to remove all the key-value pairs from the dictionary. Here's an example:
Change Value of Dictionary
To change the value of a dictionary, you can simply assign a new value to the corresponding key. Here's an example:
Output:
In the above example, we first created a dictionary my_dict
with three key-value pairs. Then we changed the value of the 'age'
key to 30
by assigning a new value to it. Finally, we printed the updated dictionary.
Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
clear()
Removes all items from the dictionary
copy()
Returns a shallow copy of the dictionary
fromkeys(seq[, v])
Returns a new dictionary with keys from seq
and value v
get(key[,d])
Returns the value of the key key
. If the key doesn't exist, returns d
(defaults to None
)
items()
Returns a view object of the dictionary's (key, value) pairs
keys()
Returns a view object of the dictionary's keys
pop(key[,d])
Removes the key and returns the associated value. If the key doesn't exist and d
is not provided, raises a KeyError
. If d
is provided, returns d
popitem()
Removes and returns an arbitrary (key, value) pair. Raises a KeyError
if the dictionary is empty
setdefault(key[,d])
Returns the value of the key. If the key doesn't exist, inserts the key with a value of d
(defaults to None
)
update([other])
Updates the dictionary with the key/value pairs from other
. If a key already exists in the dictionary, its value is updated
values()
Returns a view object of the dictionary's values
Dictionary Membership Test
In Python, we can use the in
keyword to check if a key is present in a dictionary. Here is an example:
Output:
We can also use the not in
keyword to check if a key is not present in a dictionary. Here is an example:
Output:
Iterating Through a Dictionary
You can iterate through a dictionary using a for loop to access each key-value pair of the dictionary. Here is an example:
Output:
In this example, the items()
method is used to access the key-value pairs of the dictionary, and then a for loop is used to iterate through the pairs. The key
and value
variables are used to store the key and value of each pair in each iteration of the loop.
Looping Techniques with Dictionaries
In Python, there are several looping techniques that can be used to iterate through a dictionary. Here are some of them:
Looping through keys:
We can use a for
loop to iterate over the keys of a dictionary. Here's an example:
Output:
Looping through values:
We can also use a for
loop to iterate over the values of a dictionary. Here's an example:
Output:
Looping through key-value pairs:
We can use a for
loop to iterate over the key-value pairs of a dictionary using the items()
method. Here's an example:
Output:
Using List Comprehensions:
We can also use list comprehensions to iterate over the keys, values, or items of a dictionary. Here are some examples:
Output:
Built-in Functions with Dictionaries
len()
Returns the number of items (key-value pairs) in a dictionary
str()
Produces a printable string representation of a dictionary
type()
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type
dict()
Constructor method to create a dictionary
clear()
Removes all elements of dictionary dict
copy()
Returns a shallow copy of dictionary dict
fromkeys()
Returns a new dictionary with keys from seq
and values set to value(default is None)
get(key, default)
Returns the value for the given key if it exists, else returns the default value
items()
Returns a list of the key-value pairs in the dictionary
keys()
Returns a list of the keys in the dictionary
values()
Returns a list of the values in the dictionary
pop(key)
Removes and returns the value for the given key if it exists, else returns the default value
popitem()
Removes and returns an arbitrary key-value pair from the dictionary
update()
Adds dictionary dict2
to dictionary dict
Last updated