字典經常使用於存儲鍵值對的集合,它是一種無序,可修改而且不容許重複,字典是用 {}
來表示,並帶有 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"] }
本質上來講,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...