zoukankan      html  css  js  c++  java
  • python4

    字典

    定义:字典是无序的,它不能通过偏移来存取,只能通过键来存取。

    特点:内部没有顺序,通过键来读取内容,可嵌套,方便我们组织多种数据结构,并且可以原地修改里面的内容,属于可变类型。

    创建字典。{},dict()

    a = {'name':'lilei', 'age':25}

    a = dict(name = 'lilei', age = 25)

    添加

    >>> a['phone'] = 'xiaomi'
    >>> a
    {'phone': 'xiaomi', 'age': 22, 'name': 'lilei'}

    修改

    >>> a['phone'] = 'MI8'
    >>> a
    {'phone': 'MI8', 'age': 22, 'name': 'lilei'}

    删除

    1.del// 删除指定项内容

    >>> del a['phone']
    >>> a
    {'age': 22, 'name': 'lilei'}

    2.clear()// 清空字典

    >>> a.clear()
    >>> a
    {}

    3.pop()// 删除指定项,并返回

    >>> a = {'name':'lilei', 'age':25}
    >>> a
    {'age': 25, 'name': 'lilei'}
    >>> a.pop('name')
    'lilei'
    >>> a
    {'age': 25}

    >>> a.pop('none')// 当删除的键在a中不存在时,会出错

    >>> a.pop('none', "other")// 但是可以设置默认值,当被删除的键不存在时,返回默认值('other')
    'other'

    in 和 has_key() 成员关系操作

    >>> a = {'name':'lilei', 'age':25}
    >>> 'name' in a
    True
    >>> 'ccc' in a
    False
    >>> a.has_key('name')
    True
    >>> a.has_key('ccc')
    False

    keys(): 返回的是列表,里面包含了字典的所有键

    values():返回的是列表,里面包含了字典的所有值

    items:生成一个字典的容器:[()]

    >>> a = {'name':'lilei', 'age':25}
    >>> a.keys()
    ['age', 'name']
    >>> a.values()
    [25, 'lilei']
    >>> a.items()
    [('age', 25), ('name', 'lilei')]

    get:从字典中获得一个值

    >>> a = {'name':'lilei', 'age':25}
    >>> a.get('name')
    'lilei'
    >>> a.get('ccc')// 当get内的键在a中不存在,返回空
    >>>

    // 但是可以设置默认值,当键找不到时返回默认值

    >>> a.get('ccc', 'Nothing')
    'Nothing'

  • 相关阅读:
    弹出框位置设置
    Spring Boot 发布 jar 包转为 war 包秘籍
    Oracle 动态sql小例子
    [转]ORACLE EXECUTE IMMEDIATE 小结
    [转]Java web 开发 获取用户ip
    SQLServer2008 使用sql语句访问excel数据
    Oracle 循环调用存储过程
    JavaScript 判断手机端操作系统(Andorid/IOS)
    Oracle 当输入参数允许为空时
    Oracle 生成数据字典
  • 原文地址:https://www.cnblogs.com/dulianyong/p/10063662.html
Copyright © 2011-2022 走看看