Dictionary
字典罕用于存储键值对的汇合,它是一种无序,可批改并且不容许反复, 字典是用 {}
来示意,并带有 k/v 键值对,比方上面定义的字典构造。
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 来获取字典中的内容,如下代码所示:
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。
字典是可批改的,意味着咱们能够在已创立的字典中批改,新增,删除项。
不容许反复
不容许反复,意味着同一个 key 不可能有两个 item, 有些敌人可能就要问了,如果在新增时遇到反复的 key 怎么办呢?python 中会默认笼罩掉之前同名 key,如下代码所示:
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()
办法即可,比方上面的代码:
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 等,如下代码所示:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
实质上来说,dict 就是一个名为 dict 的 class 类,如下代码所示:
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…