Python中的dict

風掠丶幽蘭發表於2018-11-19

dict_lst = [

  (`字典的鍵必須可雜湊`,),

  (`字典的鍵重複覆蓋`,),

  (`字典可迭代`)

  (`增`,),

  (`刪`,),

  (`改`,),

  (`查`,),

  (`練習`,),

]

 

字典的鍵必須可雜湊

  (PS: key-value查詢效率高)

  >>>dic = {[0]: 1}

  TypeError: unhashable type: `list`

字典的鍵重複覆蓋

  >>>dic = {`k`: 1, `k`: 2, `k`: 3}

  >>>dic

  {`k`: 3}

字典可迭代

  >>>from collections import Iterable

  >>>isinstance(dict(), Iterable)

  True

  >>>dic = {`k1`: 1, `k2`: 2}

  >>>dic[`k3`] = [3, 4]

  >>>dic

  {`k1`: 1, `k2`: 2, `k3`: [3, 4]}

  >>>dic = {`k1`: 1, `k2`: 2}

  >>>`key existed` if `k3` in dic else dic.setdefault(`k3`, 4)

  4

  >>>dic

  {`k1`: 1, `k2`: 2, `k3`: 4}

  >>>dic = {`k1`: 1, `k2`: 2, `k3`: 3}

  >>>dic.pop(`k1`)

  1

  >>>dic

  {`k2`: 2, `k3`: 3}

  >>>dic = {`k1`: 1, `k2`: 2, `k3`: 3}

  >>>dic.popitem()

  (`k3`, 3)

  >>>dic

  {`k1`: 1, `k2`: 2}

  >>>dic.clear()

  >>>dic

  {}

  >>>del dic

  >>>dic

  NameError: name `dic` is not defined

  >>>dic = {`k1`: 1, `k2`: 2}

  >>>dic[`k1`] = 4

  >>>dic

  {`k1`: 4, `k2`: 2}

  >>>dic_1 = {`k1`: 1, `k2`: 2}

  >>>dic_2 = {`k3`: 3}

  >>>dic_2.update(dic_1)

  >>>dic_2

  {`k3`: 3, `k1`: 1, `k2`: 2}

  >>>dic = {`name`: `hopen`, `age`: 1}

  >>>for key in dic:

  …    key, dic[key]

  …

  (`name`, `hopen`)

  (`age`, 1)

 

練習

  更改字典的鍵

    >>>dic = {`k1`: 1, `k2`: 2}

    >>>dic[`k4`] = dic.pop(`k1`)

    >>>dic

    {`k2`: 2, `k4`: 1}

 

 

 

  

相關文章