Mục lục bài viết

Ở bài Cấu trúc dữ liệu Dictionary trong Python, các bạn đã tìm hiểu về Dictionary. Trong bài này, chúng ta cùng xem xét một số thao tác có thể thực hiện trên Dictionary trong Python.

1. Duyệt từng phần tử trong Dictionary

Sử dụng vòng lặp for để lấy từng key trong Dictionary. Với các key lấy ra được, chúng ta có thể lấy được value của chúng.

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])
Kết quả
key: name - value: John
key: yearofbirth - value: 2000
key: class - value: 12A1      
key: math - value: 9.5
key: english - value: 10

Chúng ta cũng có thể sử dụng vòng lặp for với hàm keys(), values() hoặc items() để duyệt các phần tử trong 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)
Kết quả
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. Sao chép (copy) Dictionary trong Python

Python hỗ trợ phương thức copy() để sao chép một 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)
Kết quả
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}

Một cách khác để sao chép một Dictionary là sử dụng hàm dict().

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)
Kết quả
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 trong Python

Chúng ta có thể tạo một Dictionary bao gồm các Dictionary khác. Các Dictionary này được gọi là Nested Dictionary.

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)
Kết quả
students: {'student1': {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}, 'student2': {'name': 'Kane', 'yearofbirth': 2002, 'class': '11B1'}, 'student3': {'name': 'Son', 'yearofbirth': 2001, 'class': '12A2'}}

Chúng ta cũng có thể tạo ra từng Dictionary rồi tạo một Dictionary bao gồm các Dictionary đã có.

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)
Kết quả
students: {'student1': {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}, 'student2': {'name': 'Kane', 'yearofbirth': 2002, 'class': '11B1'}, 'student3': {'name': 'Son', 'yearofbirth': 2001, 'class': '12A2'}}

4. Các phương thức (method) của Dictionary

Python hỗ trợ nhiều method để giúp thao tác với Dictionary dễ dàng hơn. Một số method thường sử dụng với Dictionary được mô tả ở bảng bên dưới.

Phương thứcChức năng
clear()Xóa tất cả phần tử trong Dictionary
copy()Trả về một bản sao chép của Dictionary
fromkeys()Tạo ra một Dictionary mới với những key và value được xác định trước
get()Trả về value của một key cụ thể trong Dictionary
items()Trả về một list bao gồm mỗi cặp key và value được lưu trữ trong một Tuple
keys()Trả về một list bao gồm tất cả key của Dictionary
pop()Xóa một phần tử trong Dictionary với một key cụ thể
popitem()Xóa phần tử (cặp key-value) cuối cùng được thêm vào Dictionary
setdefault()Trả về value của một key cụ thể trong Dictionary. Nếu key đó không tồn tại trong Dictionary thì thêm key với một value cụ thể vào Dictionary
update()Thêm vào Dictionary với các cặp key-value cụ thể (thường là nằm trong một Dictionary khác)
values()Trả về một list gồm tất cả value trong Dictionary

Sử dụng method fromkeys() của 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)
Kết quả
my_dict using fromkeys(): {'key1': 1, 'key2': 1, 'key3': 1}
my_dict using fromkeys(): {'key1': None, 'key2': None, 'key3': None}

Sử dụng method setdefault() của 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)
Kết quả
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}

Sử dụng method update() của 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)
Kết quả
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}
Tác giả

Vinh Lê

Giảng viên CNTT, chia sẻ tutorial lập trình & phần cứng tại Góc Học IT. Hơn 500 bài viết hướng dẫn từ cơ bản đến nâng cao.

Gợi ý tiếp theo

Lỗi (error) và ngoại lệ (exception) trong Python

Học tiếp