Dict trong Python

Dict trong Python

Phan Nhật Chánh

Chánh01 tháng 10, 2020

6 min read
·
views
·
likes

Trong Python, Dictionary là một kiểu dữ liệu lưu trữ các giá trị theo dạng key-value. Mỗi phần tử trong dictionary được định nghĩa bằng một key duy nhất và một giá trị được gán cho key đó.

Dict (Dictionary) tương tự như như ListTuple. Điểm khác biệt là những container như List, Tuple có các index để phân biệt các phần tử thì Dict dùng các "key":"value" để phân biệt.

Dict là một tập hợp các kiểu dữ liệu không có thứ tự được khởi tạo với cặp dấu ngoặc nhọn {key: value}, những gì nằm trong đó là những phần tử của Dict và được cách nhau bởi dấu phẩy , Mỗi phần tử của Dict có dạng "key":"value" (ví dụ {"name": "Tèo", "age": "20"})

data = {"name": "Nguyễn Thị Bưởi"} name=data["name"] print(name) #KQ: Nguyễn Thị Bưởi data = { "name": "Nguyễn Thị Bưởi", "location": "Việt Nam" } print(data.keys()) #KQ: dict_keys(['name', 'location']) print(list(data.keys())) #KQ: ['name', 'location'] print(list(data.keys())[0]) #KQ: name data["job"] = "Coder" print(data) #KQ: {'name': 'Nguyễn Thị Bưởi', 'location': 'Việt Nam', 'job': 'Coder'} user_1 = {"name": "Nguyễn Văn Tèo"} user_2 = {"name": "Trần Văn Tý"} my_users = [user_1, user_2] print(my_users) #KQ: [{'name': 'Nguyễn Văn Tèo'}, {'name': 'Trần Văn Tý'}]
data = {"name": "Nguyễn Thị Bưởi"} name=data["name"] print(name) #KQ: Nguyễn Thị Bưởi data = { "name": "Nguyễn Thị Bưởi", "location": "Việt Nam" } print(data.keys()) #KQ: dict_keys(['name', 'location']) print(list(data.keys())) #KQ: ['name', 'location'] print(list(data.keys())[0]) #KQ: name data["job"] = "Coder" print(data) #KQ: {'name': 'Nguyễn Thị Bưởi', 'location': 'Việt Nam', 'job': 'Coder'} user_1 = {"name": "Nguyễn Văn Tèo"} user_2 = {"name": "Trần Văn Tý"} my_users = [user_1, user_2] print(my_users) #KQ: [{'name': 'Nguyễn Văn Tèo'}, {'name': 'Trần Văn Tý'}]

Tạo Dict

Để tạo một dictionary, chúng ta sử dụng cặp dấu ngoặc nhọn {}

# Ví dụ 1 empty_dict = {} dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } }
# Ví dụ 1 empty_dict = {} dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } }

Ví dụ trên cho thấy rằng giá trị của Dict có thể là bất kỳ kiểu dữ liệu khác nhau ví dụ như: string, boolean, list, tuple, set hoặc một dictionary.

Độ dài Dict

Là số lượng của cặp {key: value} trong Dict. Cũng tương tự như list, tuple để đếm số lượng dict ta sử dụng hàm len()

# Ví dụ 1 print(len(dct)) # 4 # Ví dụ 2 print(len(person)) # 7
# Ví dụ 1 print(len(dct)) # 4 # Ví dụ 2 print(len(person)) # 7

Truy cập Dict

Ta có thể truy cập đến các phần tử bằng cách sử dụng tên key của nó

# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct['key1']) # value1 print(dct['key4']) # value4 # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } print(person['first_name']) # Messi print(person['country']) # Argentina print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] print(person['skills'][0]) # JavaScript print(person['address']['street']) # Space street print(person['city']) # Error
# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct['key1']) # value1 print(dct['key4']) # value4 # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } print(person['first_name']) # Messi print(person['country']) # Argentina print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] print(person['skills'][0]) # JavaScript print(person['address']['street']) # Space street print(person['city']) # Error

Việc truy cập một phần tử theo tên key sẽ gây ra lỗi nếu key đó không tồn tại. Để tránh lỗi này, trước tiên chúng ta phải kiểm tra xem key có tồn tại hay không hoặc chúng ta có thể sử dụng phương thức get. Phương thức get sẽ trả về kết quả là None nếu key đó không tồn tại.

person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } print(person.get('first_name')) # Messi print(person.get('country')) # Argentina print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python'] print(person.get('city')) # None
person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } print(person.get('first_name')) # Messi print(person.get('country')) # Argentina print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python'] print(person.get('city')) # None

Thêm items vào dict

Chúng ta có thể thêm {key: value} vào một dict bằng cách sau:

# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct['key5'] = 'value5' print (dct) # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'} # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], # HTML 'address':{ 'street':'Space street', 'zipcode':'02214' } # 'job_title':'Instructor' } person['job_title'] = 'Instructor' person['skills'].append('HTML') print(person)
# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct['key5'] = 'value5' print (dct) # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'} # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], # HTML 'address':{ 'street':'Space street', 'zipcode':'02214' } # 'job_title':'Instructor' } person['job_title'] = 'Instructor' person['skills'].append('HTML') print(person)

Edit Dict

Ta có thể sửa đổi các value trong dict bằng cách

# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct['key1'] = 'value-one' # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } person['last_name'] = 'Thiago' person['age']
# Ví dụ 1 dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct['key1'] = 'value-one' # Ví dụ 2 person = { 'first_name':'Messi', 'last_name':'Leonel', 'age':250, 'country':'Argentina', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02214' } } person['last_name'] = 'Thiago' person['age']

Kiểm tra key có tồn tại

Chúng ta có thể sử dụng toán tử in để kiểm tra xem key có tồn tại trong dict hay không

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print('key2' in dct) # True print('key5' in dct) # False
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print('key2' in dct) # True print('key5' in dct) # False

Xóa key:value

- pop (key) : xóa mục có tên key được chỉ định: - popitem () : loại bỏ mục có key cuối cùng - del : loại bỏ một mục có key được chỉ định

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.pop('key1') # xóa key1 (jey được chỉ định) print(dct) dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.popitem() # xóa key cuối cùng print(dct) del dct['key2'] # xóa key được chỉ định print(dct)
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.pop('key1') # xóa key1 (jey được chỉ định) print(dct) dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.popitem() # xóa key cuối cùng print(dct) del dct['key2'] # xóa key được chỉ định print(dct)

Dictionary thành List

Phương thức items()items() thay đổi dict thành một list.

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])

Clear

Để xóa các cặp giá trị trong dict, chúng ta có thể xóa chúng bằng phương thức clear()clear() (làm rỗng dict)

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct.clear()) # None
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct.clear()) # None

Delete

Nếu bạn không sử dụng nữa, chúng ta có thể xóa nó hoàn toàn bằng cách (sử dụng del)

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} del dct
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} del dct

Copy

Chúng ta có thể sao chép một dictionary bằng phương thức copy()copy().

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}

Lấy key của dict và đưa vào list

Phương thức key()key() trả về kêt quả tất cả các key của dict dưới dạng một list.

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} keys = dct.keys() print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} keys = dct.keys() print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])

Lấy value của dict và đưa vào list

Phương thức values()values() trả về kêt quả tất cả các value của dict dưới dạng một list.

dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} values = dct.values() print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} values = dct.values() print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])

Bài tập

  1. Tạo một Dictionary rỗng có tên là dog.
  2. Thêm tên, màu sắc, giống, chân, tuổi vào dog.
  3. Tạo Dictionary dành cho student và thêm first_name, last_name, gender, age, marital_status, skills, country, cityaddress làm key cho dict.
  4. Nhận độ dài của dict student.
  5. Nhận giá trị skills và kiểm tra kiểu dữ liệu, nó phải là một list?
  6. Sửa đổi các giá trị skills bằng cách thêm một hoặc hai skills
  7. Lấy tất cả các key và lưu vào list.
  8. Lấy tất cả các value và lưu vào list.
  9. Thay đổi dict thành list bằng cách sử dụng phương thức items()items()
  10. Xóa một cập key:value trong dict.
  11. Xóa student