1. 程式人生 > >python--字典類型

python--字典類型

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必須用不可變對象。

    技術分享

  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

    技術分享

    技術分享

  3. 字典值的訪問
    直接通過key訪問


    技術分享


  4. 循環遍歷訪問技術分享

    技術分享


  5. 字典key-value的添加
    dic[key] = value 通過這個操作,我們會發現字典是無序的數據類型

    技術分享

    技術分享

  6. 字典的更新

    dic.update(dic1)

    技術分享





  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‘}
    技術分享
    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


    技術分享

    技術分享

  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‘]

    技術分享

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

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

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

    技術分享

  9. 示例:技術分享

    技術分享

    技術分享


    技術分享

    技術分享

python--字典類型