Sử dụng dictionary

Các kiểu dữ liệu trong Python

Jason Myers

Instructor

Tạo và lặp qua dictionary

  • Lưu dữ liệu theo cặp key/value
  • Có thể lồng (dictionary làm value của một key trong dictionary)
  • Có thể lặp
  • Tạo bằng dict() hoặc {}
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Các kiểu dữ liệu trong Python

In trong vòng lặp

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Các kiểu dữ liệu trong Python

Tìm theo key một cách an toàn

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • Lấy value từ dictionary bằng cách dùng key làm chỉ mục
  • Nếu key không tồn tại, chương trình dừng với lỗi KeyError
Các kiểu dữ liệu trong Python

Tìm theo key (tiếp)

  • .get() cho phép truy cập key an toàn, không cần xử lý lỗi/ngoại lệ
  • Nếu key không có, .get() trả về None mặc định hoặc giá trị bạn cung cấp
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Các kiểu dữ liệu trong Python

Ayo berlatih!

Các kiểu dữ liệu trong Python

Preparing Video For Download...