8.字典dict

作者: Stone_説 | 来源:发表于2020-12-14 12:48 被阅读0次

    目录
    0.字典介绍
    1.字典定义和初始化
    2.字典元素访问
    3.字典添加和修改
    4.字典删除
    5.字典遍历
    6.字典遍历和移除
    7.defaultdict
    8.OrderedDict

    0.字典介绍

    key-value键值对存储的集合
    key一定是要可hash的类型
    可变,无需,key不重复

    1.字典定义和初始化

    d = dict()或者d={}

    >>> d = dict()
    >>> d,type(d)
    ({}, <class 'dict'>)
    >>> d = {}
    >>> d,type(d)
    ({}, <class 'dict'>)
    

    dict(**kwargs)使用name=value对初始化一个字典

    >>> d = dict(a=1,b=2,c=3)
    >>> d,type(d)
    ({'a': 1, 'b': 2, 'c': 3}, <class 'dict'>)
    

    dict(iterable,**kwargs)使用可迭代对象和name=value对构造字典,不过可迭代对象的元素必须是一个二元结构

    >>> d = dict(((1,'a'),(2,'b')))
    >>> d,type(d)
    ({1: 'a', 2: 'b'}, <class 'dict'>)
    >>> d = dict(([1,'a'],[2,'b']))
    >>> d,type(d)
    ({1: 'a', 2: 'b'}, <class 'dict'>)
    

    dict(mapping,**kwargs)使用一个字典构建另一个字典
    d={'a':10,'b':20,'c':None,'d':[1,2,3]}
    类方法dict.fromkeys(iterable,value)

    >>> d = dict.fromkeys(range(5))
    >>> d,type(d)
    ({0: None, 1: None, 2: None, 3: None, 4: None}, <class 'dict'>)
    >>> d = dict.fromkeys(range(5),0)
    >>> d,type(d)
    ({0: 0, 1: 0, 2: 0, 3: 0, 4: 0}, <class 'dict'>)
    

    2.字典元素访问

    2.1 d[key]

    返回key对应的值value
    key不存在抛出KeyError异常

    >>> d = dict(a=1,b=2,c=3)
    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> d['a']
    1
    >>> d[a]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: None
    
    2.2 get(key[,default])

    返回key对应的值value
    key不存在返回却省值,如果没有设置缺省值就返回None

    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> d.get('a')
    1
    >>> d.get('m')
    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> d.get('m')
    >>> d.get('m',4)
    4
    
    2.3 setdefault(key[,default])

    返回key对应的值value
    key不存在,添加kv对,value为default,并返回default,如果default没有设置,缺省为None

    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> d.setdefault('b')
    2
    >>> d.setdefault('d')
    >>> d
    {'a': 1, 'b': 2, 'c': 3, 'd': None}
    >>> d.setdefault('e',5)
    5
    >>> d
    {'a': 1, 'b': 2, 'c': 3, 'd': None, 'e': 5}
    

    3.字典添加和修改

    3.1 d[key]=value

    将key对应的值修改为value,key不存在添加新的kv对

    >>> d = {'a': 1, 'b': 2, 'c': 3}
    >>> d['a']=4
    >>> d
    {'a': 4, 'b': 2, 'c': 3}
    
    3.2 update([other]) -> None

    使用另一个字典的kv对更新本字典,key不存在就添加,key存在,覆盖对应的值,原地修改
    dict1.update(dict2)

    >>> d
    {'a': 4, 'b': 2, 'c': 3}
    >>> d
    {'a': 4, 'b': 2, 'c': 3}
    >>> d.update((('red',2),))
    >>> d
    {'a': 4, 'b': 2, 'c': 3, 'red': 2}
    >>> d.update({'red':3})
    >>> d
    {'a': 4, 'b': 2, 'c': 3, 'red': 3}
    >>> d.update(a=100)
    >>> d
    {'a': 100, 'b': 2, 'c': 3, 'red': 3}
    

    4.字典删除

    4.1 pop(key[,default])

    key存在,移除它,并返回它的value
    key不存在,返回给定的default
    default未设置,key不存在则抛出KeyError异常

    >>> d
    {'a': 100, 'b': 2, 'c': 3, 'red': 3}
    >>> d.pop('a')
    100
    >>> d.pop('b',23)
    2
    >>> d.pop('b',23)
    23
    >>> d.pop('b')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'b'
    
    4.2 popitem()

    移除并返回一个任意的键值对
    字典为empty,抛出KeyError异常

    >>> d = {'a': 4, 'b': 2, 'c': 3, 'red': 3}
    >>> d.popitem()
    ('red', 3)
    ...
    >>> d.popitem()
    ('a', 4)
    >>> d.popitem()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'popitem(): dictionary is empty'
    
    4.3 clear()
    >>> d = {'a': 4, 'b': 2, 'c': 3, 'red': 3}
    >>> d.clear()
    >>> d
    {}
    
    4.4 del语句
    a = True
    b = [6]
    d = {'a': 1, 'b': b, 'c': [1,3,5]}
    del a
    del d['c']
    del b[0]
    c = b
    del c
    del b
    b = d['b']
    p del a['c'] 减少了一个对象的引用,del 实际上删除的是名称,而不是对象
    

    5.字典遍历

    5.1 遍历key

    for ... in dict

    >>> d = {'a':1,'b':2,'c':3}
    >>> for k in d:
    ...     print(k)
    a
    b
    c
    >>> for k in d.keys():
    ...     print(k)
    a
    b
    c
    
    5.2 遍历value

    for ... in dict

    >>> d = {'a':1,'b':2,'c':3}
    >>> for k in d:
    ...     print(d[k])
    1
    2
    3
    >>> for k in d.keys():
    ...     print(d.get(k))
    1
    2
    3
    >>> for v in d.values():
    ...     print(v) 
    1
    2
    3
    
    5.3 遍历item,即kv对

    for ... in dict

    >>> d = {'a':1,'b':2,'c':3}
    >>> for item in d.items():
    ...     print(item,type(item))
    ... 
    ('a', 1) <class 'tuple'>
    ('b', 2) <class 'tuple'>
    ('c', 3) <class 'tuple'>
    >>> for item in d.items():
    ...     print(item[0],item[1])
    a 1
    b 2
    c 3
    >>> for k,v in d.items():
    ...     print(k,v)
    a 1
    b 2
    c 3
    >>> for k,_ in d.items():
    ...     print(k)
    a
    b
    c
    >>> for _,v in d.items():
    ...     print(v)
    1
    2
    3
    

    6.字典遍历和移除

    6.1 错误的移除方法
    >>> d
    {'a': 1, 'b': 2, 'c': 3}
    >>> for k,v in d.items():
    ...     d.pop(k)
    1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    RuntimeError: dictionary changed size during iteration
    
    6.2 正确的移除方法

    方法一:相当于清空,不如clear()方法

    >>> d
    {'b': 2, 'c': 3}
    >>> while len(d):
    ...     print(d.popitem())
    ('c', 3)
    ('b', 2)
    >>> d = {'a': 1, 'b': 2, 'c': 3}
    >>> d.clear()
    >>> d
    {}
    

    方法二:

    >>> d = {'a': 1, 'b': 2, 'c': 'd'}
    >>> keys = []
    >>> for k,v in d.items():
    ...     if isinstance(v,int):
    ...             keys.append(k)
    >>> keys
    ['a', 'b']
    >>> for k in keys():
    KeyboardInterrupt
    >>> for k in keys:
    ...     d.pop(k)
    1
    2
    >>> d
    {'c': 'd'}
    

    7.defaultdict

    collections.default([default_factory[,...]])
    第一个参数是default_factory,缺省是None,提供一个初始化函数
    当key不存在时,会调用这个工厂函数来生成key对应的value

    >>> import random
    >>> d1 = {}
    >>> for k in 'abcdef':
    ...     for i in range(random.randint(1,5)):
    ...             if k not in d1.keys():
    ...                     d1[k] = []
    ...             d1[k].append(i)
    >>> d1
    {'a': [0, 1, 2, 3, 4], 'b': [0], 'c': [0], 'd': [0, 1], 'e': [0, 1, 2, 3], 'f': [0, 1, 2, 3, 4]}
    
    >>> from collections import defaultdict
    >>> import random
    >>> d1 = defaultdict(list)
    >>> 
    >>> for k in 'abcdef':
    ...     for i in range(random.randint(1,5)):
    ...             d1[k].append(i)
    ... 
    >>> d1
    defaultdict(<class 'list'>, {'a': [0, 1], 'b': [0, 1, 2, 3, 4], 'c': [0], 'd': [0, 1], 'e': [0, 1, 2, 3, 4], 'f': [0, 1]})
    

    8.OrderedDict

    collections.OrderedDict([items])
    key并不是按照加入的顺序排列,可以使用OrderedDict记录顺序

    >>> from collections import OrderedDict
    >>> import random
    >>> d = {'b':3,'a':4,'p':1,'o':2}
    >>> d
    {'b': 3, 'a': 4, 'p': 1, 'o': 2}
    >>> keys = list(d.keys())
    >>> keys
    ['b', 'a', 'p', 'o']
    >>> random.shuffle(keys)
    >>> keys
    ['a', 'b', 'o', 'p']
    >>> od = OrderedDict()
    >>> for key in keys:
    ...     od[key] = d[key]
    ... 
    >>> od
    OrderedDict([('a', 4), ('b', 3), ('o', 2), ('p', 1)])
    >>> od.keys()
    odict_keys(['a', 'b', 'o', 'p'])
    

    相关文章

      网友评论

        本文标题:8.字典dict

        本文链接:https://www.haomeiwen.com/subject/fhrmgktx.html