Dictionaries in Python

Python offers a range of data types referred to as sequences. In this article today, we will be learning about dictionaries in Python. We will be defining what a dictionary is and learning different ways of creating dictionaries. Thereafter, we will also be learning different ways of manipulating dictionaries in Python. We will also learn to delete a dictionary.

 

What are Dictionaries in Python?

Dictionary is an unordered collection of values in Python. Dictionaries are similar to lists but instead of storing values only as elements, it holds the key: value pairs.

 

Now let us look at different operations we can perform on a dictionary.

 

Creating a dictionary:

A dictionary is very simple to create in Python. We can create a dictionary by writing a sequence of elements in braces “{}” separated by commas. By elements, we mean key: value pairs. The keys are immutable and are unique. There can be more than one occurrence of a value. We can also create a dictionary by using the dict() method.

 

The below code snippet shows the methods of creating a dictionary:
# creating a empty dictionary using braces
my_dict = {}
print(my_dict)

print()

# creating a dictionary with key:value pairs
my_dict = {'A': 'Hello', 'B': 'World', 'C': 'Program'}
print(my_dict)

print()

# dictionary with mixed keys
my_dict = {1: 'Hello', 'B': 'World', 'X': 'Program'}
print(my_dict)

print()

# creating a empty dictionary with dict() method
my_dict = dict()
print(my_dict)

print()

# creating a dictionary with elements with dict()
my_dict = dict({1: 'Hello', 2: 'World', 3: 'Program'})
print(my_dict)
Output:
{}

{'A': 'Hello', 'B': 'World', 'C': 'Program'}

{1: 'Hello', 'B': 'World', 'X': 'Program'}

{}

{1: 'Hello', 2: 'World', 3: 'Program'}

Note: Keys in a dictionary are case sensitive. Therefore, two keys having the same name but different cases are considered distinct keys.

 

Adding Elements to a Dictionary:

Adding an element to a dictionary is similar to adding an element to a list. Instead of passing the index, we pass the key to the dictionary. If the key: value pair is already present, then the value is updated. Otherwise, a new key: value pair is added to the dictionary.

 

We can add a nested key: value pair to a dictionary by assigning another dictionary to a key.

 

The below code snippet shows adding elements to a dictionary:
# creating a dictionary
my_dict = {}
print(my_dict)

print()

# adding elements to the dictionary
my_dict[0] = 'Hello'
my_dict[1] = 'World'
my_dict[2] = 'Program'
print(my_dict)

print()

# updating the value of a key
my_dict[2] = '!!!'
print(my_dict)

print()

# adding a nested value
my_dict[3] = {'5': {1: 'Hello', 2: 'World'}}
print(my_dict)
Output:
{}

{0: 'Hello', 1: 'World', 2: 'Program'}

{0: 'Hello', 1: 'World', 2: '!!!'}

{0: 'Hello', 1: 'World', 2: '!!!', 3: {'5': {1: 'Hello', 2: 'World'}}}

 

Accessing elements from a Dictionary:

Accessing an element from a dictionary is very similar to accessing an element from a list. We pass the key of the element we want to retrieve in the square brackets instead of the index. We can also use the get() method to retrieve values paired with keys.

 

The below code snippet shows accessing elements from a dictionary:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

print()

# accessing an element
a = my_dict[1]
b = my_dict[2]
print(a)
print(b)

# accessing an element using get()
a = my_dict.get(3)
print(a)
Output:
{1: 'Hello', 2: 'World', 3: 'Program'}

Hello
World
Program

 

Deleting elements from a dictionary:

There are multiple ways to remove elements from a dictionary. There are built-in methods we can use remove elements from a dictionary. Let us learn these methods one by one.

 

1. clear(): The clear() method removes all the elements from the dictionary. The clear() method works the same way with lists and dictionaries.

 

Syntax:
dictionary_name.clear()

 

The below code snippet shows the working of the clear() method:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

print()

my_dict.clear()
print(my_dict)
Output:
{1: 'Hello', 2: 'World', 3: 'Program'}

{}

 

2. pop(): The pop() method removes the element from the dictionary whose key is specified. It deletes the key: value pair. The popped element can be stored in a variable.

 

Syntax:
dictionary_name.pop(key)

 

The below code snippet shows the working of the pop() method:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

print()

# deleting an element using pop()
a = my_dict.pop(3)
print('The popped value is:', a)
print(my_dict)
Output:
{1: 'Hello', 2: 'World', 3: 'Program'}

The popped value is: Program

{1: 'Hello', 2: 'World'}

 

3. popitem(): The popitem() method removes a random key: value pair from a dictionary. Like the pop() method the key: value pair popped by the popitem() method can also be stored in a variable.

 

Syntax:
dictionary_name.popitem()

 

The below code snippet shows the working of popitem() method:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

print()

# deleting an element using popitem()
a = my_dict.popitem()
print('The popped key: value pair is:', a)
print(my_dict)
Output:
{1: 'Hello', 2: 'World', 3: 'Program'}

The popped key: value pair is: (3, 'Program')

{1: 'Hello', 2: 'World'}

 

4. del(): The del() method is similar to the pop() method. The only difference is the del() method does not return the deleted key: value pair.

 

Syntax:
del(dictionary_name[key])

 

The below code snippet shows the working of del() method:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

print()

# deleting an element using del()
del(my_dict[3])
print(my_dict)
Output:
{1: 'Hello', 2: 'World', 3: 'Program'}

{1: 'Hello', 2: 'World'}

 

We can use other built-in methods concerning dictionaries in python. We can use the dir() method to get a list of all the methods that can be used with dictionaries.

 

The below code snippet shows the dictionary methods:
# dictionary methods
my_dict = {}
methods = dir(my_dict)
print(methods)
Output:
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', 
'__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
 '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get',
 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

 

Deleting a dictionary:

We can delete a dictionary by using the del() method. We pass the name of the dictionary as a parameter to the del() method.

 

Syntax:
del(dictionary_name)

 

The below code snippet depicts deleting a dictionary:
# creating a dictionary
my_dict = {1: 'Hello', 2: 'World', 3: 'Program'}
print(my_dict)

# deleting a dictionary
del my_dict
print(my_dict)
Output:
NameError: name 'my_dict' is not defined

 

This is the end of this article. Please refer to the articles called Lists in Python | Part 1 and Lists in Python | Part 2 to learn about lists in Python. The lists and dictionaries are very similar in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *