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}

  

05-26 14:34