Python 入门系列 —— 21. dict 的介绍

Dictionary

字典经常使用于存储键值对的集合,它是一种无序,可修改而且不容许重复,字典是用 {} 来表示,并带有 k/v 键值对,好比下面定义的字典结构。python

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)


PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

字典项

字典中的项是以 key-value 形式展先的,一般咱们用 key 来获取字典中的内容,以下代码所示:markdown

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict["brand"])

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Ford

无序,可修改

当咱们说字典是无序的,意味着它并无一个预先定义好的顺序,也就不能经过 index 的方式去获取 dictionary 中的 item。app

字典是可修改的,意味着咱们能够在已建立的字典中修改,新增,删除项。this

不容许重复

不容许重复,意味着同一个key 不可能有两个 item,有些朋友可能就要问了,若是在新增时遇到重复的 key 怎么办呢? python 中会默认覆盖掉以前同名key,以下代码所示:code

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

字典长度

要想判断字典中有多少个 item,能够使用 len() 方法便可,好比下面的代码:get

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}

print(len(thisdict))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
3

字典项的数据类型

字典项的value值能够是任何类型,好比 int,string,array 等,以下代码所示:string

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

type()

本质上来讲,dict 就是一个名为 dict 的 class 类,以下代码所示:it

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
<class 'dict'>
译文连接: https://www.w3schools.com/pyt...
相关文章
相关标签/搜索