1. 程式人生 > >python--字典和集合

python--字典和集合

all true dict err 嵌套 emp 操作 style trace

字典

字典一種key - value 的數據類型

語法:

info={
     01:Tom,
     02:Jim,
     03:Lucy‘,
     04:Lily 
 }

字典的特性:

  • dict是無序的
  • key必須是唯一的,所以自動去重

增加:

In [20]: info[05]=Hans

In [21]: print(info)
{02: Jim, 03: Lucy, 01: Tom, 04: Lily, 05: Hans}

修改:

In [22]: info[03]=LiGang

In [
23]: print(info) {02: Jim, 03: LiGang, 01: Tom, 04: Lily, 05: Hans}

刪除:

刪除有兩種方法:

dict.pop(key)  #第一種方法 
In [24]: info.pop(‘01‘)
Out[24]: ‘Tom‘

In [25]: print(info)
{‘02‘: ‘Jim‘, ‘03‘: ‘LiGang‘, ‘04‘: ‘Lily‘, ‘05‘: ‘Hans‘}
del dict[key]  #第二種方法
In [26]: del info[‘05‘]

In [27]: print(info)
{‘02‘: ‘Jim‘, ‘03‘: ‘LiGang‘, ‘04‘: ‘Lily‘}

還有一種是隨機刪除

dict.popitem()  #隨機刪除字典裏的key和value
In [29]: info.popitem()
Out[29]: (03, LiGang)

In [30]: info.popitem()
Out[30]: (04, Lily)

In [31]: info.popitem()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-203673e70575> in <module>() ----> 1 info.popitem() KeyError: popitem(): dictionary is empty In [32]: print(info) {}

查找:

In [35]: info
Out[35]: {‘01‘: ‘Tom‘, ‘02‘: ‘Jim‘, ‘03‘: ‘Lucy‘, ‘04‘: ‘Lily‘}
In [34]: ‘01‘ in info   #標準用法
Out[34]: True

In [36]: info.get(‘01‘)  #獲取
Out[36]: ‘Tom‘

  

多級字典嵌套及操作:

 

  

  

  

  

  

python--字典和集合