• 数据类型之字典


    字典(dict)是一个kv即键值存储库,是python中唯一的映射类型,官方叫做 Mapping Type。

    字典是可变数据类型,即可以对元素重新赋值,以及修改元素值。字典不是序列,它是无序的。

    字典通过key获取元素值,而不是索引编号。在访问或删除key时,如果key不存在,会抛出 KeyError 异常。

    字典用花括号{}表示,元素是k:v键值对,用逗号隔开。键必须是不可变类型,比如数字、字符串和元组,元祖中的元素也必须是不可变类型。

    看看官方说明:

    A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.
    
    Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}, or by the dict constructor.
    

    语法格式:

    dict(**kwarg)
    dict(mapping, **kwarg)
    dict(iterable, **kwarg)
    
    Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
    
    If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
    
    If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
    

    在对字典中的元素赋值时,如果key不存在,则添加一个元素。

    创建字典时,如果没有给定位置参数,则创建一个空字典。

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

    创建字典的方法:

    >>> a = dict(one=1, two=2, three=3)
    >>> b = {'one': 1, 'two': 2, 'three': 3}
    >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
    >>> e = dict({'three': 3, 'one': 1, 'two': 2})
    >>> a == b == c == d == e
    True
    

    这几种都表示同一个字典:{"one": 1, "two": 2, "three": 3}

    删除字典中的元素用del:del d['key']或者del(d['key'])

    示例:

    >>> user={'name':'keith','age':18,'tel':110}
    >>> user['addr']='wuhan'
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan'}
    >>> del user['addr']
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110}
    

    遍历字典:

    >>> user={'name':'keith','age':18,'tel':110}
    >>> for i in user:
    ... 	print(i)
    ...
    name
    age
    tel
    

    这样遍历只输出了key名称,其实是可以同时输出key和value的,后面说。

    内置函数

    >>> dir(d)
    ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
    

    clear:清空字典中的元素。

    >>> help(d.clear)
    Help on built-in function clear:
    
    clear(...) method of builtins.dict instance
        D.clear() -> None.  Remove all items from D.
    

    copy:复制一个字典。shadow copy就是常说的深复制,即创建一个新的字典对象,占用的新的内存地址。

    >>> help(d.copy)
    Help on built-in function copy:
    
    copy(...) method of builtins.dict instance
        D.copy() -> a shallow copy of D
    
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110}
    >>> user2=user.copy()
    >>> user2['addr']='wuhan'
    >>> user2
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan'}
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110}
    

    get:获取元素值。这里可以定义一个默认值,如果key存在则返回元素值,如果不存在,则返回默认值,默认值如果没有指定,则默认为None。

    >>> help(d.get)
    Help on built-in function get:
    
    get(...) method of builtins.dict instance
        D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
    
    >>> user={'name':'keith','age':18,'tel':110}
    >>> user.get('name')
    'keith'
    >>> user.get('addr')
    >>> print(user.get('addr'))
    None
    >>> user.get('addr','beijing')
    'beijing'
    >>> user['addr']='wuhan'
    >>> user.get('addr','beijing')
    'wuhan'
    

    setdefault:字面意思是设置默认值,与get类似,也可以用来获取元素值,不同的是,它可以为元素赋值。如果key存在,则返回元素值;如果key不存在,则新建一个元素。如果未设置默认值,则默认为None。

    >>> help(d.setdefault)
    Help on built-in function setdefault:
    
    setdefault(...) method of builtins.dict instance
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
    
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan'}
    >>> user.setdefault('sex',1)
    1
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan', 'sex': 1}
    # 当sex不存在时,新建了一个元素。再次访问时,这时sex已经存在,即便给定了新的值也不会重新赋值,还是返回原来定义的value。
    >>> user.setdefault('sex',0)
    1
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan', 'sex': 1}
    >>> user.setdefault('school')
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110, 'addr': 'wuhan', 'school': None}
    

    fromkeys:根据给定的序列创建一个新的字典,如果没有指定value,则value默认为None。

    >>> help(d.fromkeys)
    Help on built-in function fromkeys:
    
    fromkeys(iterable, value=None, /) method of builtins.type instance
        Returns a new dict with keys from iterable and values equal to value.
    
    >>> user.fromkeys(['name','age','tel'])
    {'name': None, 'age': None, 'tel': None}
    >>> user.fromkeys(['name','age','tel'],'xx')
    {'name': 'xx', 'age': 'xx', 'tel': 'xx'}
    

    keys:返回所有key,这里返回的是一个dictionary view对象,由于keys都是唯一的而且可hash的,所以这里是一个类set对象,支持set的操作。

    >>> help(d.keys)
    Help on built-in function keys:
    
    keys(...) method of builtins.dict instance
        D.keys() -> a set-like object providing a view on D's keys
    
    >>> user={'name': 'keith', 'age': 18, 'tel': 110}
    >>> user.keys()
    dict_keys(['name', 'age', 'tel'])
    >>> list(user.keys())
    ['name', 'age', 'tel']
    

    values:返回所有value,这里返回的也是一个dictionary view对象。

    >>> help(d.values)
    Help on built-in function values:
    
    values(...) method of builtins.dict instance
        D.values() -> an object providing a view on D's values
    
    >>> user.values()
    dict_values(['keith', 18, 110])
    >>> list(user.values())
    ['keith', 18, 110]
    

    items:这里返回的也是一个dictionary view对象。将字典中的元素的kv转换为元祖列表。如果keys和values都是可hash的,那么items view将也是一个类set对象。

    >>> help(d.items)
    Help on built-in function items:
    
    items(...) method of builtins.dict instance
        D.items() -> a set-like object providing a view on D's items
    
    >>> user.items()
    dict_items([('name', 'keith'), ('age', 18), ('tel', 110)])
    >>> type(user.items())
    <class 'dict_items'>
    >>> list(user.items())
    [('name', 'keith'), ('age', 18), ('tel', 110)]
    

    这里再来说一下遍历:

    >>> user={'name': 'keith', 'age': 18, 'tel': 110}
    >>> for i in user.items():
    ... 	print(i)
    ...
    ('name', 'keith')
    ('age', 18)
    ('tel', 110)
    

    这样就可以同时获取元素的key和value了,不过这里返回的是元祖,你可能想要用冒号分开的格式,解包一下就可以。

    >>> for k,v in user.items():
    ... 	print(k,':',v)
    ...
    name : keith
    age : 18
    tel : 110
    

    update:用来更新数据。

    >>> help(dict.update)
    Help on method_descriptor:
    update(...)
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
    
    >>> user={}
    >>> user.update({'name':'keith','age':29})
    >>> user
    {'name': 'keith', 'age': 29}
    >>> user.update({'age':30,'addr':'shanxi'})
    >>> user
    {'name': 'keith', 'age': 30, 'addr': 'shanxi'}
    

    pop:用来删除元素,删除指定key对应的元素,并返回value,注意,返回的是value,而不是整个元素。这里也可以给一个默认值,如果key不存在,则返回默认值,如果没有给定默认值,则会抛出KeyError异常。默认值只有在key不存在时才会被返回,如果key存在,就只会返回key本身的value。

    >>> help(dict.pop)
    Help on method_descriptor:
    pop(...)
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
    
    >>> user
    {'name': 'keith', 'age': 18, 'tel': 110}
    >>> user.pop('tel')
    110
    >>> user
    {'name': 'keith', 'age': 18}
    >>> user.pop('addr')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'addr'
    >>> user.pop('addr','wuhan')
    'wuhan'
    >>> user.pop('age',0)
    18
    >>> user
    {'name': 'keith'}
    

    另外,pop必须跟至少一个参数,不然会抛出TypeError异常。

    >>> user.pop()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: pop expected at least 1 arguments, got 0
    

    popitem:也是用来删除元素,不过这里会同时返回kv组成的元祖。这里不带参数,直到字典被清空。如果字典为空,则会抛出KeyError异常。

    >>> help(dict.popitem)
    Help on method_descriptor:
    popitem(...)
        D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
    
    >>> user.popitem()
    ('tel', 110)
    >>> user.popitem()
    ('age', 18)
    >>> user.popitem()
    ('name', 'keith')
    >>> user.popitem()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'popitem(): dictionary is empty'
    

    从python3.6开始,字典默认就是有序的了,叫做Ordereddict,所以使用popitem每次删除的总是最后一个元素。

    参考:
    https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
    http://www.runoob.com/python3/python3-att-dictionary-popitem.html
    https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6
    https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects

  • 相关阅读:
    oracle rank() 排名函数
    oracle rank over partition by
    oracle over函数
    oracle extract函数
    mybatis的<choose>和<when>、<otherwise>标签
    python字符串操作实方法大合集
    GO安全并发之无锁原子操作
    设计模式(Design Patterns)Java版
    Linux内核参数调优
    TCP协议解析
  • 原文地址:https://www.cnblogs.com/keithtt/p/7630409.html
Copyright © 2020-2023  润新知