使用字典

Python 的数据类型

Jason Myers

Instructor

创建并遍历字典

  • 以键/值对存储数据
  • 可嵌套(字典的值可为字典)
  • 可迭代
  • dict(){} 创建
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Python 的数据类型

在循环中打印

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Python 的数据类型

安全按键查找

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

KeyError: 'Louvre'
  • 使用键作为索引从字典取值
  • 访问不存在的键会触发 KeyError 并终止程序
Python 的数据类型

安全按键查找(续)

  • .get() 可安全访问键,无需错误/异常处理
  • 键不存在时,.get() 默认返回 None,也可提供返回值
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Python 的数据类型

让我们来练习!

Python 的数据类型

Preparing Video For Download...