Từ điển là một trong những cấu trúc dữ liệu được sử dụng nhiều nhất trong Python. Từ điển là một tập hợp các mục không có thứ tự và chúng tôi thường có các khóa và giá trị được lưu trữ trong từ điển. Chúng ta hãy xem xét một vài ví dụ về cách từ điển thường được sử dụng.
# dictionary declaration 1
dict1 = dict()
# dictionary declaration 2
dict2 = {}
# Add items to the dictionary
# The syntax to add and retrieve items is same for either of the two objects we defined above.
key = "X"
value = "Y"
dict1[key] = value
# The dictionary doesn't have any specific data-type.
# So, the values can be pretty diverse.
dict1[key] = dict2
Bây giờ chúng ta hãy xem xét một số cách truy xuất.
# Since "X" exists in our dictionary, this will retrieve the value
value = dict1[key]
# This key doesn't exist in the dictionary.
# So, we will get a `KeyError`
value = dict1["random"]
Tránh KeyError: Sử dụng chức năng .get
Trong trường hợp khóa đã cho không tồn tại trong từ điển, Python sẽ ném ra một KeyError
. Có một cách giải quyết đơn giản cho việc này. Hãy xem làm thế nào chúng ta có thể tránh KeyError
sử dụng tích hợp sẵn .get
chức năng cho từ điển.
dict_ = {}
# Some random key
random_key = "random"
# The most basic way of doing this is to check if the key
# exists in the dictionary or not and only retrieve if the
# key exists. Otherwise not.
if random_key in dict_:
print(dict_[random_key])
else:
print("Key = {} doesn't exist in the dictionary".format(dict_))
Rất nhiều lần chúng tôi đồng ý nhận một giá trị mặc định khi khóa không tồn tại. Ví dụ: khi xây dựng một bộ đếm. Có một cách tốt hơn để lấy các giá trị mặc định từ từ điển trong trường hợp thiếu khóa hơn là dựa vào tiêu chuẩn if-else
.
# Let's say we want to build a frequency counter for items in the following array
arr = [1,2,3,1,2,3,4,1,2,1,4,1,2,3,1]
freq = {}
for item in arr:
# Fetch a value of 0 in case the key doesn't exist. Otherwise, fetch the stored value
freq[item] = freq.get(item, 0) + 1
Nên get(<key>, <defaultval>)
là một thao tác tiện dụng để truy xuất giá trị mặc định cho bất kỳ khóa đã cho nào từ từ điển. Vấn đề với phương pháp này xuất hiện khi chúng ta muốn xử lý các cấu trúc dữ liệu có thể thay đổi dưới dạng các giá trị, ví dụ: list
hoặc set
.
dict_ = {}
# Some random key
random_key = "random"
dict_[random_key] = dict_.get(random_key, []).append("Hello World!")
print(dict_) # {'random': None}
dict_ = {}
dict_[random_key] = dict_.get(random_key, set()).add("Hello World!")
print(dict_) # {'random': None}
Bạn có thấy vấn đề không?
Cái mới set
hoặc là list
không được gán cho khóa của từ điển. Chúng ta nên chỉ định một cái mới list
hoặc một set
vào khóa trong trường hợp thiếu giá trị và sau đó append
hoặc add
tương ứng. Ley xem xét một ví dụ cho điều này.
dict_ = {}
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
print(dict_) # {'random': set(['Hello World!'])}. Yay!
Tránh KeyError: Sử dụng defaultdict
Điều này làm việc hầu hết thời gian. Tuy nhiên, có một cách tốt hơn để làm điều này. nhiều hơn pythonic
đường. Các defaultdict
là một lớp con của lớp dict tích hợp. Các defaultdict
chỉ cần gán giá trị mặc định mà chúng tôi chỉ định trong trường hợp thiếu khóa. Vì vậy, hai bước:
dict_[random_key] = dict_.get(random_key, set())
dict_[random_key].add("Hello World!")
bây giờ có thể được kết hợp thành một bước duy nhất. ví dụ
from collections import defaultdict
# Yet another random key
random_key = "random_key"
# list defaultdict
list_dict_ = defaultdict(list)
# set defaultdict
set_dict_ = defaultdict(set)
# integer defaultdict
int_dict_ = defaultdict(int)
list_dict_[random_key].append("Hello World!")
set_dict_[random_key].add("Hello World!")
int_dict_[random_key] += 1
"""
defaultdict(<class 'list'>, {'random_key': ['Hello World!']})
defaultdict(<class 'set'>, {'random_key': {'Hello World!'}})
defaultdict(<class 'int'>, {'random_key': 1})
"""
print(list_dict_, set_dict_, int_dict_)
Tài liệu chính thức