測試環境為 CentOS 8 x86_64 (虛擬機)
一般宣告的 List(串列)資料型態,其資料不好搜尋到,這時候可以使用 dic ( dictionary ),資料是由 key (鍵值,可使用 括字串(str),整數(int)與浮點數(float) ) + Value (值,可以為任何東西)
定義使用大括號{} 來表示為 dic ,內的格式為 key:valu ( pair 組成 並由逗點隔開) 如下.
Computer1={"CPU":"Intel" , "MEM":["Hynix 16G","Hynix 16G"] , "Disk":"Samsung"}
要存取 dic 只需指定其 Key 值(陣列可以指定位置).
[root@localhost ~]# vi dic1.py Computer1={"CPU":"Intel" , "MEM":["Hynix 16G","Hynix 16G"] , "Disk":"Samsung"} print(Computer1["CPU"]) print(Computer1["MEM"]) print(Computer1["MEM"][0])
執行結果.
[root@localhost ~]# python3 dic1.py Intel ['Hynix 16G', 'Hynix 16G'] Hynix 16G
如資料不存在會回傳 Error ,建議透過 dic 的 get (method) 來存取.
[root@localhost ~]# vi dic2.py Computer1={"CPU":"Intel" , "MEM":["Hynix 16G","Hynix 16G"] , "Disk":"Samsung"} print(Computer1["IO"])
執行結果.
[root@localhost ~]# python3 dic2.py Traceback (most recent call last): File "dic2.py", line 2, in <module> print(Computer1["IO"]) KeyError: 'IO'
[root@localhost ~]# vi dic3.py Computer1={"CPU":"Intel" , "MEM":["Hynix 16G","Hynix 16G"] , "Disk":"Samsung"} print(Computer1.get("CPU" , 'Not Found')) print(Computer1.get("IO" , 'Not Found'))
執行結果.
[root@localhost ~]# python3 dic3.py Intel Not Found
要檢視 Key 值.
[root@localhost ~]# vi dic4.py Computer1={"CPU":"Intel" , "MEM":["Hynix 16G","Hynix 16G"] , "Disk":"Samsung"} print(Computer1.keys()) print(Computer1.values())
執行結果.
[root@localhost ~]# python3 dic4.py dict_keys(['CPU', 'MEM', 'Disk']) dict_values(['Intel', ['Hynix 16G', 'Hynix 16G'], 'Samsung'])
以下是 dic 物件的 method , 參考文件 – https://docs.python.org/3/library/stdtypes.html#typesmapping
- list(d)
- len(d)
- iter(d)
- clear()
- copy()
- get(key[, default])
- items()
- keys()
- pop(key[, default])
- popitem()
- reversed(d)
- setdefault(key[, default])
- update([other])
- update()
- values()
沒有解決問題,試試搜尋本站其他內容