✌️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:

# create a dictionary
person = {'name': 'John', 'age': 30, 'city': 'New York'}

# print the dictionary
print(person)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

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:

my_dict = {"name": "John", "age": 28, "location": "New York"}

print(my_dict["name"])    # Output: John
print(my_dict["age"])     # Output: 28

Example using the get() method:

my_dict = {"name": "John", "age": 28, "location": "New York"}

print(my_dict.get("name"))    # Output: John
print(my_dict.get("age"))     # Output: 28

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).

my_dict = {"name": "John", "age": 28, "location": "New York"}

print(my_dict["occupation"])          # Output: KeyError: 'occupation'
print(my_dict.get("occupation"))      # Output: None
print(my_dict.get("occupation", "-")) # Output: -

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:

# create a dictionary
my_dict = {'apple': 2, 'banana': 4, 'orange': 1}

# update the value of 'apple'
my_dict['apple'] = 3

# add a new key-value pair
my_dict['pear'] = 5

print(my_dict)  # {'apple': 3, 'banana': 4, 'orange': 1, 'pear': 5}

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.

  1. Using the del keyword:

We can use the del keyword to remove a specific key-value pair from the dictionary. Here's an example:

my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
del my_dict['gender']
print(my_dict)   # Output: {'name': 'John', 'age': 25}
  1. 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:

my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
removed_value = my_dict.pop('gender')
print(my_dict)           # Output: {'name': 'John', 'age': 25}
print(removed_value)     # Output: 'male'
  1. Using the clear() method:

We can use the clear() method to remove all the key-value pairs from the dictionary. Here's an example:

my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
my_dict.clear()
print(my_dict)   # Output: {}

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:

# create a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# change the value of 'age' key
my_dict['age'] = 30

# print the updated dictionary
print(my_dict)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

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.

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:

my_dict = {'a': 1, 'b': 2, 'c': 3}

if 'a' in my_dict:
    print('Key "a" is present in the dictionary')
else:
    print('Key "a" is not present in the dictionary')

Output:

Key "a" is present in the dictionary

We can also use the not in keyword to check if a key is not present in a dictionary. Here is an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}

if 'd' not in my_dict:
    print('Key "d" is not present in the dictionary')
else:
    print('Key "d" is present in the dictionary')

Output:

Key "d" is not present in the dictionary

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:

my_dict = {"apple": 2, "banana": 4, "orange": 1}

# iterating through the dictionary
for key, value in my_dict.items():
    print(key, value)

Output:

apple 2
banana 4
orange 1

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:

  1. Looping through keys:

We can use a for loop to iterate over the keys of a dictionary. Here's an example:

my_dict = {'apple': 3, 'banana': 2, 'orange': 1}

for key in my_dict:
    print(key)

Output:

apple
banana
orange
  1. Looping through values:

We can also use a for loop to iterate over the values of a dictionary. Here's an example:

my_dict = {'apple': 3, 'banana': 2, 'orange': 1}

for value in my_dict.values():
    print(value)

Output:

3
2
1
  1. 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:

my_dict = {'apple': 3, 'banana': 2, 'orange': 1}

for key, value in my_dict.items():
    print(key, value)

Output:

apple 3
banana 2
orange 1
  1. Using List Comprehensions:

We can also use list comprehensions to iterate over the keys, values, or items of a dictionary. Here are some examples:

my_dict = {'apple': 3, 'banana': 2, 'orange': 1}

# List comprehension to get all the keys
keys = [key for key in my_dict]
print(keys)

# List comprehension to get all the values
values = [value for value in my_dict.values()]
print(values)

# List comprehension to get all the key-value pairs
items = [(key, value) for key, value in my_dict.items()]
print(items)

Output:

['apple', 'banana', 'orange']
[3, 2, 1]
[('apple', 3), ('banana', 2), ('orange', 1)]

Built-in Functions with Dictionaries

Last updated