Operations on Dictionary Data Structure in Python

This post is lesson 29 of 54 in the subject Python Programming Language

In the article Dictionary data structure in Python, you learned about Dictionary. In this article, we will consider some operations on a Dictionary data structure in Python.

1. Loop through each element in Dictionary

Use the for loop to retrieve each key in the Dictionary. With the keys obtained, we can get their values.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "math": 9.5,
  "english": 10
}
for x in my_dict:
  print("key:", x, "-", "value:", my_dict[x])

Result

key: name - value: John
key: yearofbirth - value: 2000
key: class - value: 12A1
key: math - value: 9.5
key: english - value: 10

We can also use the for loop with the keys(), values(), or items() function to iterate through the elements in the Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "math": 9.5,
  "english": 10
}
# loop through my_dict using keys()
print("keys in my_dict:", end=' ')
for x in my_dict.keys():
  print(x, end=' ')

# loop through my_dict using values()
print("\nvalues in my_dict:", end=' ')
for x in my_dict.values():
  print(x, end=' ')

# loop through my_dict using items()
print("\nkeys and values in my_dict:")
for x, y in my_dict.items():
  print("key:", x, "-", "value:", y)

Result

keys in my_dict: name yearofbirth class math english
values in my_dict: John 2000 12A1 9.5 10
keys and values in my_dict:
key: name - value: John
key: yearofbirth - value: 2000
key: class - value: 12A1
key: math - value: 9.5
key: english - value: 10

2. Copying a Dictionary in Python

Python supports the copy() method to copy a dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "math": 9.5,
  "english": 10
}
print("my_dict:", my_dict)
my_dict_copy = my_dict.copy()
print("my_dict_copy:", my_dict_copy)

Result

my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 10}
my_dict_copy: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 10}

Another way to copy a Dictionary is to use the dict() function.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "math": 9.5,
  "english": 10
}
print("my_dict:", my_dict)
my_dict_copy = dict(my_dict)
print("my_dict_copy:", my_dict_copy)

Result

my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 10}
my_dict_copy: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 10}

3. Nested Dictionary in Python

We can create a Dictionary that includes other Dictionaries. These Dictionaries are called Nested Dictionaries.

students = {
  "student1": {
      "name": "John",
      "yearofbirth": 2000,
      "class": "12A1"
  },
  "student2": {
      "name": "Kane",
      "yearofbirth": 2002,
      "class": "11B1"
  },
  "student3":{
      "name": "Son",
      "yearofbirth": 2001,
      "class": "12A2"
  }
}
print("students:", students)

Result

students: {'student1': {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}, 'student2': {'name': 'Kane', 'yearofbirth': 2002, 'class': '11B1'}, 'student3': {'name': 'Son', 'yearofbirth': 2001, 'class': '12A2'}}

We can also create each Dictionary first and then create a Dictionary that includes the existing Dictionaries.

student1 = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
student2 = {
  "name": "Kane",
  "yearofbirth": 2002,
  "class": "11B1"
}
student3 = {
  "name": "Son",
  "yearofbirth": 2001,
  "class": "12A2"
}
students = {
  "student1": student1,
  "student2": student2,
  "student3": student3,
}
print("students:", students)

Result

students: {'student1': {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}, 'student2': {'name': 'Kane', 'yearofbirth': 2002, 'class': '11B1'}, 'student3': {'name': 'Son', 'yearofbirth': 2001, 'class': '12A2'}}

4. Methods of Dictionary

Python supports many methods to make working with Dictionary easier. Some commonly used methods with Dictionary are described in the table below.

MethodFunction
clear()Removes all the elements from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()Returns a new dictionary with specified keys and values
get()Returns the value of the specified key. If the key does not exist, it returns the default value
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary’s keys
pop()Removes and returns an element with the specified key
popitem()Removes and returns the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist, it inserts the key with the specified value
update()Updates the dictionary with the specified key-value pairs (either another dictionary or a sequence of key-value pairs)
values()Returns a list of all the values in the dictionary

Using the fromkeys() method of Dictionary

# fromkeys() with specified key and value
x = ("key1", "key2", "key3")
y = 1
fromkeys_my_dict = dict.fromkeys(x, y)
print("my_dict using fromkeys():", fromkeys_my_dict)

# fromkeys() with only specified key
fromkeys_my_dict = dict.fromkeys(x)
print("my_dict using fromkeys():", fromkeys_my_dict)

Result

my_dict using fromkeys(): {'key1': 1, 'key2': 1, 'key3': 1}
my_dict using fromkeys(): {'key1': None, 'key2': None, 'key3': None}

Using the setdefault() method of Dictionary

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("my_dict:", my_dict)
# setdefault()
x = my_dict.setdefault("class", "10A2")
print("x = ", x)
print("my_dict after setdefault():", my_dict)
# setdefault()
x = my_dict.setdefault("math", 9.5)
print("x = ", x)
print("my_dict after setdefault():", my_dict)

Result

my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}
x =  12A1
my_dict after setdefault(): {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}
x =  9.5
my_dict after setdefault(): {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5}

Using the update() method of Dictionary

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("my_dict:", my_dict)
my_dict.update({"math": 9.5})
print("my_dict after update():", my_dict)
# update update_dict to my_dict
update_dict = {
  "english": 9.5,
  "literature": 8.5
}
my_dict.update(update_dict)
print("my_dict after update():", my_dict)

Result

my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}
my_dict after update(): {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5}
my_dict after update(): {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 9.5, 'literature':
8.5}
5/5 - (1 vote)
Previous and next lesson in subject<< Dictionary Data Structure in PythonErrors and Exceptions in Python >>

Leave a Reply

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