zoukankan      html  css  js  c++  java
  • 字典的操作

    删除

    del

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> del people['age']
    >>> people
    {'kind': 'beauty'}

    pop

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> people.pop('age')
    '22'
    >>> people
    {'kind': 'beauty'}

    popitem 删除一个,不带参数(字典是无序的,不确定会删除哪个)

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> people.popitem()
    ('kind', 'beauty')
    >>> people
    {'age': '22'}
    

    增、改

    setdefault 如果不存指定键在就新增,存在不做任何操作

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> people.setdefault('like', 'sport')
    'sport'
    >>> people
    {'kind': 'beauty', 'like': 'sport', 'age': '22'}
    >>> people.setdefault('kind', 'fool')
    'beauty'
    >>> people
    {'kind': 'beauty', 'like': 'sport', 'age': '22'}

    update 很常用,直接修改或新增

    get  没取到为None(也可设置为其它)

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> like = people.get('like')
    >>> like
    >>> print like
    None

    in 是否存在该键(Python2里还有has_key也是相同用法,Python3里没有has_key)

    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> print 'kind' in people
    True
    >>> people = {'kind': 'beauty', 'age': '22'}
    >>> print('age'in people)
    True

    其它操作

    items 转换为字典

    >>> people
    {'kind': 'beauty', 'like': 'sport', 'age': '22'}
    >>> people.items()
    dict_items([('kind', 'beauty'), ('like', 'sport'), ('age', '22')])

    fromkeys 创建字典,所有的键共用一个值(修改一个,其它的都变,像浅copy)

    >>> like = dict.fromkeys(['sport', 'singing', 'dance'], '666')
    >>> like
    {'singing': '666', 'sport': '666', 'dance': '666'}
    >>> like['singing'] = 'yes'
    >>> like
    {'singing': 'yes', 'sport': '666', 'dance': '666'}
    
    >>> lau = dict.fromkeys(['C', 'Java', 'Python'], ['code', 'yes'])
    >>> lau
    {'C': ['code', 'yes'], 'Python': ['code', 'yes'], 'Java': ['code', 'yes']}
    >>> lau['Python'][1] = 'no'
    >>> lau
    {'C': ['code', 'no'], 'Python': ['code', 'no'], 'Java': ['code', 'no']}
  • 相关阅读:
    MySql 用户 及权限操作
    MAC 重置MySQL root 密码
    在mac系统安装Apache Tomcat的详细步骤[转]
    Maven:mirror和repository 区别
    ES6 入门系列
    转场动画CALayer (Transition)
    OC 异常处理
    Foundation 框架
    Enum枚举
    Invalid App Store Icon. The App Store Icon in the asset catalog in 'xxx.app' can’t be transparent nor contain an alpha channel.
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/8594952.html
Copyright © 2011-2022 走看看