关于Python3的字典方法说明

    技术2023-05-26  24

    1、字典内置方法

    >>> for i in dir(dict): ... if not i.startswith('_'): ... print(i) ... clear copy fromkeys get items keys pop popitem setdefault update values

    2、字典方法解析

    初始化一个字典

    >>> student = {'name': 'xiaoming', 'age':28, 'hobby': 'running'} >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running'} clear 移除字典中所有item >>> student.clear() >>> student {} copy 字典的浅拷贝 >>> student.copy() {'name': 'xiaoming', 'age': 28, 'hobby': 'running'} fromkeys 根据iterable创建一个新字典,默认值为None,语法:fromkeys(iterable, value=None, /) >>> keys = iter(['aa', 'bb', 'cc']) >>> dict.fromkeys(keys) {'aa': None, 'bb': None, 'cc': None} get 获取字典中指定key的值 >>> student.get('name') 'xiaoming' items 返回字典所有item的对象 >>> student.items() dict_items([('age', 28), ('hobby', 'running')]) >>> list(student.items()) [('age', 28), ('hobby', 'running')] keys 返回字典所有key的对象 >>> student.keys() dict_keys(['name', 'age', 'hobby']) >>> list(student.keys()) ['name', 'age', 'hobby'] pop 根据key移除并返回key对应的值,如果key不存在则报错:KeyError >>> student = {'name': 'xiaoming', 'age':28, 'hobby': 'running'} >>> student.pop('name') 'xiaoming' >>> student {'age': 28, 'hobby': 'running'} popitem 从字典中移除并返回最后一个二元组,如果字典为空则抛出异常:KeyError: ‘popitem(): dictionary is empty’ >>> student.popitem() ('hobby', 'running') setdefault 如果字典中不存在key则插入这个key,默认值为None;如果字典中存在这个key,就返回它的值 >>> student = {'name': 'xiaoming', 'age': 28, 'hobby': 'running'} >>> student.setdefault('name') 'xiaoming' >>> student.setdefault('aa') >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running', 'aa': None} update 用于更新字典中的键/值对,可以修改存在的键对应的值,也可以添加新的键/值对到字典中。 案例一:传入字典 >>> student.update({'aa':123}) >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running', 'aa': 123}

    案例二:传入关键字形式

    >>> student.update(bb=456, cc=567) >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running', 'aa': 123, 'bb': 456, 'cc': 567}

    案例三:列表中的元组

    >>> student.update([('dd',678), ('ee',789)]) >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running', 'aa': 123, 'bb': 456, 'cc': 567, 'dd': 678, 'ee': 789}

    案例四:利用zip构建元组

    >>> student.update(zip(['hello', 'good'], ['world','morning'])) >>> student {'name': 'xiaoming', 'age': 28, 'hobby': 'running', 'aa': 123, 'bb': 456, 'cc': 567, 'dd': 678, 'ee': 789, 'hello': 'world', 'good': 'morning'} values 返回字典所有value的对象 >>> student.values() dict_values(['xiaoming', 28, 'running']) >>> list(student.values()) ['xiaoming', 28, 'running']
    Processed: 0.014, SQL: 8