Từ điển Python (Có ví dụ)

Trong hướng dẫn này, bạn sẽ học mọi thứ về từ điển Python; cách chúng được tạo, truy cập, thêm, xóa các phần tử khỏi chúng và các phương thức tích hợp khác nhau.

Video: Từ điển Python để lưu trữ các cặp khóa / giá trị

Từ điển Python là một tập hợp các mục không có thứ tự. Mỗi mục của từ điển có một key/valuecặp.

Các từ điển được tối ưu hóa để truy xuất các giá trị khi khóa được biết.

Tạo từ điển Python

Tạo từ điển đơn giản như đặt các mục bên trong dấu ngoặc nhọn được ()phân tách bằng dấu phẩy.

Một mục có a keyvà a tương ứng valueđược biểu thị dưới dạng một cặp ( khóa: giá trị ).

Mặc dù các giá trị có thể thuộc bất kỳ kiểu dữ liệu nào và có thể lặp lại, nhưng các khóa phải thuộc loại bất biến (chuỗi, số hoặc bộ mã với các phần tử bất biến) và phải là duy nhất.

 # empty dictionary my_dict = () # dictionary with integer keys my_dict = (1: 'apple', 2: 'ball') # dictionary with mixed keys my_dict = ('name': 'John', 1: (2, 4, 3)) # using dict() my_dict = dict((1:'apple', 2:'ball')) # from sequence having each item as a pair my_dict = dict(((1,'apple'), (2,'ball')))

Như bạn có thể thấy ở trên, chúng ta cũng có thể tạo từ điển bằng dict()chức năng tích hợp sẵn.

Truy cập các phần tử từ từ điển

Trong khi lập chỉ mục được sử dụng với các kiểu dữ liệu khác để truy cập các giá trị, thì từ điển lại sử dụng keys. Các phím có thể được sử dụng bên trong dấu ngoặc vuông ()hoặc với get()phương thức.

Nếu chúng ta sử dụng dấu ngoặc vuông (), KeyErrorsẽ được nâng lên trong trường hợp không tìm thấy khóa trong từ điển. Mặt khác, get()phương thức trả về Nonenếu không tìm thấy khóa.

 # get vs () for retrieving elements my_dict = ('name': 'Jack', 'age': 26) # Output: Jack print(my_dict('name')) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict('address'))

Đầu ra

 Jack 26 Không có Traceback (cuộc gọi gần đây nhất): Tệp "", dòng 15, in (my_dict ('address')) KeyError: 'address'

Thay đổi và thêm các thành phần từ điển

Từ điển có thể thay đổi. Chúng ta có thể thêm các mục mới hoặc thay đổi giá trị của các mục hiện có bằng toán tử gán.

Nếu khóa đã có thì giá trị hiện có sẽ được cập nhật. Trong trường hợp không có khóa, một cặp ( khóa: giá trị ) mới sẽ được thêm vào từ điển.

 # Changing and adding Dictionary Elements my_dict = ('name': 'Jack', 'age': 26) # update value my_dict('age') = 27 #Output: ('age': 27, 'name': 'Jack') print(my_dict) # add item my_dict('address') = 'Downtown' # Output: ('address': 'Downtown', 'age': 27, 'name': 'Jack') print(my_dict)

Đầu ra

 ('tên': 'Jack', 'tuổi': 27) ('tên': 'Jack', 'tuổi': 27, 'địa chỉ': 'Trung tâm thành phố')

Xóa các phần tử khỏi Từ điển

Chúng tôi có thể xóa một mục cụ thể trong từ điển bằng cách sử dụng pop()phương pháp này. Phương thức này loại bỏ một mục với mục được cung cấp keyvà trả về value.

Các popitem()phương pháp có thể được sử dụng để loại bỏ và trả về một tùy (key, value)cặp mục từ điển. Tất cả các mục có thể được xóa cùng một lúc bằng clear()phương pháp này.

Chúng tôi cũng có thể sử dụng deltừ khóa để xóa từng mục hoặc toàn bộ từ điển.

 # Removing elements from a dictionary # create a dictionary squares = (1: 1, 2: 4, 3: 9, 4: 16, 5: 25) # remove a particular item, returns its value # Output: 16 print(squares.pop(4)) # Output: (1: 1, 2: 4, 3: 9, 5: 25) print(squares) # remove an arbitrary item, return (key,value) # Output: (5, 25) print(squares.popitem()) # Output: (1: 1, 2: 4, 3: 9) print(squares) # remove all items squares.clear() # Output: () print(squares) # delete the dictionary itself del squares # Throws Error print(squares)

Đầu ra

 16 (1: 1, 2: 4, 3: 9, 5: 25) (5, 25) (1: 1, 2: 4, 3: 9) () Traceback (lần gọi gần đây nhất): Tệp "", dòng 30, in (hình vuông) NameError: tên 'hình vuông' không được xác định

Phương thức từ điển Python

Các phương pháp có sẵn với từ điển được lập bảng bên dưới. Một số trong số chúng đã được sử dụng trong các ví dụ trên.

phương pháp Sự miêu tả
thông thoáng() Xóa tất cả các mục khỏi từ điển.
copy () Trả về một bản sao ngắn của từ điển.
fromkeys (seq (, v)) Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key(,d)) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key(,d)) Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key(,d)) Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update((other)) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

Here are a few example use cases of these methods.

 # Dictionary Methods marks = ().fromkeys(('Math', 'English', 'Science'), 0) # Output: ('English': 0, 'Math': 0, 'Science': 0) print(marks) for item in marks.items(): print(item) # Output: ('English', 'Math', 'Science') print(list(sorted(marks.keys())))

Output

 ('Math': 0, 'English': 0, 'Science': 0) ('Math', 0) ('English', 0) ('Science', 0) ('English', 'Math', 'Science')

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces ().

Here is an example to make a dictionary with each item being a pair of a number and its square.

 # Dictionary Comprehension squares = (x: x*x for x in range(6)) print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

This code is equivalent to

 squares = () for x in range(6): squares(x) = x*x print(squares)

Output

 (0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25)

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

Here are some examples to make a dictionary with only odd items.

 # Dictionary Comprehension with if conditional odd_squares = (x: x*x for x in range(11) if x % 2 == 1) print(odd_squares)

Output

 (1: 1, 3: 9, 5: 25, 7: 49, 9: 81)

To learn more dictionary comprehensions, visit Python Dictionary Comprehension.

Other Dictionary Operations

Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.

 # Membership Test for Dictionary Keys squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: True print(1 in squares) # Output: True print(2 not in squares) # membership tests for key only not value # Output: False print(49 in squares)

Output

 True True False

Iterating Through a Dictionary

We can iterate through each key in a dictionary using a for loop.

 # Iterating through a Dictionary squares = (1: 1, 3: 9, 5: 25, 7: 49, 9: 81) for i in squares: print(squares(i))

Output

 1 9 25 49 81

Dictionary Built-in Functions

Built-in chức năng như all(), any(), len(), cmp(), sorted(), vv được sử dụng phổ biến với các từ điển để thực hiện nhiệm vụ khác nhau.

Chức năng Sự miêu tả
tất cả() Trả về Truenếu tất cả các khóa của từ điển là Đúng (hoặc nếu từ điển trống).
bất kì() Trả lại Truenếu bất kỳ khóa nào của từ điển là đúng. Nếu từ điển trống, hãy quay lại False.
len () Trả về độ dài (số lượng mục) trong từ điển.
cmp () So sánh các mục của hai từ điển. (Không có sẵn trong Python 3)
đã sắp xếp () Trả lại danh sách khóa được sắp xếp mới trong từ điển.

Dưới đây là một số ví dụ sử dụng các hàm tích hợp để làm việc với từ điển.

 # Dictionary Built-in Functions squares = (0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81) # Output: False print(all(squares)) # Output: True print(any(squares)) # Output: 6 print(len(squares)) # Output: (0, 1, 3, 5, 7, 9) print(sorted(squares))

Đầu ra

 Sai Đúng 6 (0, 1, 3, 5, 7, 9)

thú vị bài viết...