欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python中的dict

程序员文章站 2022-12-22 22:14:27
dict_lst = [ ('字典的键必须可哈希',), ('字典的键重复覆盖',), ('字典可迭代') ('增',), ('删',), ('改',), ('查',), ('练习',), ] 字典的键必须可哈希 (PS: key-value查询效率高) >>>dic = {[0]: 1} Type ......

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}