Cấu trúc dữ liệu Dictionary trong Python

Đây là bài 28/54 bài của series môn học Ngôn ngữ lập trình Python

1. Dictionary là gì? Tạo một Dictionary trong Python

Dictionary được sử dụng để lưu trữ dữ liệu dạng keyvalue. Các phần tử trong Dictionary có thứ tự (ordered), có thể thay đổi (changeable)không có phép 2 phần tử có cùng key. Các cặp keyvalue trong Dictionary được khai báo trong dấu ngoặc nhọn {}. Các value trong Dictionary có thể có bất kỳ kiểu dữ liệu nào.

# empty dictionary
my_dict = {}
print(my_dict)
# dictionary with integer keys
my_dict = {
    1: 'apple',
    2: 'banana',
    3: 'lemon'
}
print(my_dict)
# dictionary with mixed keys
my_dict = {
  "name": "John",
  1: [2, 3, 4],
  2: "12A1"
}
print(my_dict)
# dictionary with mixed values
my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "subject": ["math", "literature", "english"]
}
print(my_dict)
# using dict() to create dictionary
my_dict = dict({1: 'apple', 2: 'banana', 3: 'lemon'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'banana'), (3, 'lemon')])
print(my_dict)
Kết quả
{}
{1: 'apple', 2: 'banana', 3: 'lemon'}
{'name': 'John', 1: [2, 3, 4], 2: '12A1'}
{'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'subject': ['math', 'literature', 'english']}
{1: 'apple', 2: 'banana', 3: 'lemon'}
{1: 'apple', 2: 'banana', 3: 'lemon'}

Không cho phép 2 phần tử trùng key trong Dictionary

Dictionary sẽ nhận giá trị của key cuối cùng trong những key bị trùng cho key đó.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "class": "IT02"
}
print(my_dict)
Kết quả
{'name': 'John', 'yearofbirth': 2000, 'class': 'IT02'}

Số lượng phần tử trong Dictionary

Sử dụng hàm len() để trả về số lượng phần tử trong Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("Number of items in my_dict:", len(my_dict))
my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1",
  "class": "IT02"
}
print("Number of items in my_dict:", len(my_dict))
Kết quả
Number of items in my_dict: 3
Number of items in my_dict: 3

2. Truy cập các phần tử trong Dictionary

Chúng ta có thể truy cập các phần tử trong Dictionary bằng cách sử dụng key trong dấu ngoặc vuông []. Ngoài ra, chúng ta cũng có thể sử dụng phương thức get().

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("Get value of 'class' key using []:", my_dict["class"])
my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("Get value of 'class' key using get():", my_dict.get("class"))
Kết quả
Get value of 'class' key using []: 12A1
Get value of 'class' key using get(): 12A1

2.1. Lấy tất cả key trong Dictionary

Phương thức keys() giúp trả về danh sách của tất cả key trong Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
all_keys = my_dict.keys()
print("All keys in my_dict:", all_keys)
Kết quả
All keys in my_dict: dict_keys(['name', 'yearofbirth', 'class'])

2.2. Lấy tất cả value trong Dictionary

Phương thức values() giúp trả về danh sách của tất cả value trong Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
all_values = my_dict.values()
print("All values in my_dict:", all_values)
Kết quả
All values in my_dict: dict_values(['John', 2000, '12A1'])

2.3. Lấy tất cả phần tử trong Dictionary

Phương thức items() giúp trả về mỗi phần tử trong Dictionary dưới dạng là mỗi Tuple trong một List.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
all_items = my_dict.items()
print("All items in my_dict:", all_items)
Kết quả
All items in my_dict: dict_items([('name', 'John'), ('yearofbirth', 2000), ('class', '12A1')])

2.4. Kiểm tra một key có tồn tại trong Dictionary hay không?

Sử dụng từ khóa in để xác định một key có tồn tại trong Dictionary hay không.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
# check yearofbirth key
if "yearofbirth" in my_dict:
  print("'yearofbirth' is one of the keys in the my_dict dictionary")
else:
  print("'yearofbirth' isnot one of the keys in the my_dict dictionary")
# check subject key
if "subject" in my_dict:
  print("'subject' is one of the keys in the my_dict dictionary")
else:
  print("'subject' isnot one of the keys in the my_dict dictionary")
Kết quả
'yearofbirth' is one of the keys in the my_dict dictionary
'subject' isnot one of the keys in the my_dict dictionary

3. Thêm, xóa, sửa các phần tử trong Dictionary

3.1. Thêm các phần tử vào Dictionary

Chúng ta có thể khai báo một key mới và gán giá trị đó cho key đó để thêm một phần tử vào Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict["math"] = 9.5
print("Add an item to my_dict:", my_dict)
Kết quả
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5}

Python có hỗ trợ hàm update() để thêm các phần tử của một Dictionary vào một Dictionary khác.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict.update({"math": 9.5, "english": 9.9})
print("Add an item to my_dict:", my_dict)
Kết quả
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1', 'math': 9.5, 'english': 9.9}

3.2. Xóa các phần tử của Dictionary

Sử dụng hàm pop()

Hàm pop() giúp xóa một phần tử trong Dictionary với một key được xác định trước.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict.pop("class")
print("Remove an item of my_dict using pop():", my_dict)
Kết quả
Remove an item of my_dict using pop(): {'name': 'John', 'yearofbirth': 2000}

Sử dụng hàm popitem()

Hàm popitem() giúp xóa phần tử cuối cùng được thêm vào Dictionary.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict.popitem()
print("Remove an item of my_dict using popitem():", my_dict)
my_dict["class"] = "12A2"
print("Add an item to my_dict:", my_dict)
my_dict.popitem()
print("Remove an item of my_dict using popitem():", my_dict)
Kết quả
Remove an item of my_dict using popitem(): {'name': 'John', 'yearofbirth': 2000}
Add an item to my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A2'}
Remove an item of my_dict using popitem(): {'name': 'John', 'yearofbirth': 2000}

Sử dụng hàm clear()

Hàm clear() giúp xóa tất cả các phần tử trong Dictionary để được Dictionary rỗng.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("my_dict:", my_dict)
my_dict.clear()
print("Clear my_dict:", my_dict)
Kết quả
my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '12A1'}
Clear my_dict: {}

Sử dụng từ khóa del

Từ khóa del sẽ xóa tất cả các phần tử trong Dictionary và cả biến tham chiếu đến Dictionary đó.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
print("my_dict:", my_dict)
del my_dict
# NameError: name 'my_dict' is not defined
#print("my_dict:", my_dict)

3.3. Sửa các phần tử trong Dictionary

Chúng ta có thể thay đổi giá trị của một key trong Dictionary bằng cách gán lại giá trị cho key đó.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict["class"] = "1A2"
print("Change an item of my_dict:", my_dict)
Kết quả
Change an item of my_dict: {'name': 'John', 'yearofbirth': 2000, 'class': '1A2'}

Chúng ta có thể thay đổi giá trị của key trong Dictionary bằng cách sử dụng hàm update() với đối số gồm key đã tồn tại trong Dictionary và một giá trị mới muốn thay đổi.

my_dict = {
  "name": "John",
  "yearofbirth": 2000,
  "class": "12A1"
}
my_dict.update({"class": "1A2"})
print("Change an item of my_dict using update():", my_dict)
Kết quả
Change an item of my_dict using update(): {'name': 'John', 'yearofbirth': 2000, 'class': '1A2'}
5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Các thao tác trên cấu trúc dữ liệu Set trong PythonCác thao tác trên cấu trúc dữ liệu Dictionary trong Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.