zoukankan      html  css  js  c++  java
  • python学习笔记之列表、元组、字典(2)

    1、字典

        a、字典可以理解为一种映射,就是一种对应关系,叫键-值对应,如键:name 对应值:sola ,字典为:{name:sola}

        同样的,像序列,元组那样,字典也有其生成函数dict

       如下:

    >>> a = [('name','sola'),('phonenum','123456')]
    >>> b = dict(a)
    >>> b
    {'phonenum': '123456', 'name': 'sola'}

    >>> b['name']
    'sola'
    >>> b['phonenum']
    '123456'

     b、字典的方法:

    clear  #清除字典中所有的项

    >>> b
    {'phonenum': '123456', 'name': 'sola'}
    >>> b.clear()
    >>> b
    {}     #返回一个空字典

    copy  #返回具有相同键值对的字典

    >>> b
    {'phonenum': '123456', 'name': 'sola'}
    >>> c = b.copy()
    >>> c
    {'phonenum': '123456', 'name': 'sola'}

    fromkeys #使用给定的键,建立新的字典,每个键对应一个默认值None

    >>> c = {}.fromkeys(['name','class'])
    >>> c
    {'name': None, 'class': None}
    >>> c['name'] = 'sola'
    >>> c
    {'name': 'sola', 'class': None}

    get #用于访问字典中的项,即使项不存在,还可以自定义默认返回值

    >>> c
    {'name': 'sola', 'class': None}
    >>> c.get('name')
    'sola'
    >>> c.get('home')
    >>> c.get('home','meizhou')
    'meizhou'

    has_key #检查字典中是否含有特定的键。类似成员方法

    >>> c
    {'name': 'sola', 'class': None}
    >>> c.has_key('name')
    True
    >>> c.has_key('home')
    False

    items,iteritems  #items 将字典中所有的项以列表的形式返回,列表中每一项为(键,值)对,iteritems返回一个迭代器对象(可以理解为把字典所有的项以一个集合的形式返回,并不像列表那样一个一个的项)

    >>> b
    {'phonenum': '123456', 'name': 'sola'}
    >>> b.items()
    [('phonenum', '123456'), ('name', 'sola')]
    >>> b.iteritems()
    <dictionary-itemiterator object at 0x022D5660>
    >>> items = b.iteritems()

    >>> for item in items:
    ... print item
    ...
    ('phonenum', '123456')
    ('name', 'sola')

    keys,iterkeys #keys将字典中的键以列表的形式返回,而iterkeys返回针对键的迭代器

    values,itervalues #values将字典中的值以列表的形式返回,itervalues返回针对值的迭代器

    >>> b.keys()
    ['phonenum', 'name']
    >>> b.values()
    ['123456', 'sola']

    update  #可以利用一个字典项更新另外一个字典项

    >>> b
    {'phonenum': '123456', 'name': 'sola'}
    >>> c
    {'home': 'meizhou', 'country': 'china'}
    >>> b.update(c)
    >>> b
    {'name': 'sola', 'country': 'china', 'home': 'meizhou', 'phonenum': '123456'}

  • 相关阅读:
    python note 30 断点续传
    python note 29 线程创建
    python note 28 socketserver
    python note 27 粘包
    python note 26 socket
    python note 25 约束
    Sed 用法
    python note 24 反射
    python note 23 组合
    python note 22 面向对象成员
  • 原文地址:https://www.cnblogs.com/sola-tester/p/4109615.html
Copyright © 2011-2022 走看看