python--字典类型

******************   字典类型   ******************

  1. 为什么需要字典类型?
    >>> list1 = ["name", "age", "gender"]
    >>> list2 = ["fentiao", 5, "male"]
    >>> zip(list1, list2)
    //通过zip内置函数将两个列表结合,help(zip)
    [('name', 'fentiao'), ('age', 5), ('gender', 'male')]

    >>> list2[0]Out[12]:
    //在直接编程时,并不能理解第一个索引表示姓名
    'fentiao'
    >>> list2[name]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: list indices must be integers, not str
    故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。

    python--字典类型

  2. 字典的定义
    简单字典创建

     >>> dic = {"name":"fentiao", "age":5, "gender":"male"}
     >>> dic[0]   //不能通过索引提取value值
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      KeyError: 0
      >>> dic["name"]    //根据key找出value值
      'fentiao'

    内建方法:fromkeys
        字典中的key有相同的value值,默认为None

         python--字典类型

    python--字典类型

  3. 字典值的访问
    直接通过key访问


    python--字典类型


  4. 循环遍历访问python--字典类型

    python--字典类型


  5. 字典key-value的添加
    dic[key] = value  通过这个操作,我们会发现字典是无序的数据类型

    python--字典类型

    python--字典类型

  6. 字典的更新

    dic.update(dic1)

    python--字典类型





  7. 字典的删除
    dic.pop(key) 根据key值删除字典的元素;

     >>> dic
      {'gender': 'male', 'age': 8, 'name': 'fentiao', 'kind': 'cat'}
      >>> dic.pop("kind")   //弹出字典中key值为"kind"的元素并返回该key的元素
      'cat'
     >> dic
    {'gender': 'male', 'age': 8, 'name': 'fentiao'}
     python--字典类型
    dic.popitem() 随机删除字典元素,返回(key,value)

     >>>dic.popitem()
      ('gender', 'male')

      >>> dic
     {'age': 5, 'name': 'fentiao'}
    dic.clear() 删除字典中的所有元素

     >>> dic.clear()   //删除字典的所有元素Out[22]:
     >>> dic
     {}
    del dic 删除字典本身

    >>> del dic                    //删除整个字典
     >>> dic
     Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     NameError: name 'dic' is not defined


    python--字典类型

    python--字典类型

  8. 字典的常用方法
    dict.get()   如果key存在于字典中,返回对应value值

     >>>dic.get('age')
     5
     >>>dic.get('gender')
     'male'
    dic.keys()  返回字典的所有key值

     >>>dic.keys()
     ['gender', 'age', 'name']

    dic.values() 返回字典的所有value值

     >>>dic.values()
     ['male', 5, 'fentiao']

    python--字典类型

    dict.has_key() 字典中是否存在某个key值

     >>>dic.has_key('name')
     True
     >>>dic.has_key('age')
     True
    dic.items()

    >>>dic.items()
    [('gender', 'male'), ('age', 5), ('name', 'fentiao')]

    python--字典类型

  9. 示例:python--字典类型

    python--字典类型

         python--字典类型


    python--字典类型

    python--字典类型


本文转自cuijb0221 51CTO博客,原文链接:http://blog.51cto.com/cuijb/1948172