• Python中的字典(Dictionary)


    在Python中,字典(Dictionary)是一个常见的数据结构,它可以存储任意类型的对象。

    创建字典

    字典由键和值组成,字典中所有键值均要放在 大括号 {} 里面,键与值之间通过
    冒号 : 分割,而每一对键值之间则通过 逗号 , 间隔起来,其格式如下:

    d = {key1: value1, key2: value2, key3: value3}
    

    一般在创建字典时,分为创建空字典和非空字典,其创建方式如下:

    # 创建空字典,有两种方式
    dict1= dict()
    dict2 = {}
    
    # 创建非空字典
    dict3 = {"name": ["hello", "world"], "age": 13, 666: True}
    

    在上面的 dict3 中,包含了 3 个键值对,其中键 "name" 对应值为一个列表 ["hello", "world"],键 "age" 对应值为一个整数 13,键 666 对应值为一个布尔值True。

    需要注意的是,字典中的键必须是唯一的,同时字典的键必须是不可变对象,如 字符串、数字 等,而键对应的值,则可以是任意数据类型。

    到这里,我们思考一个问题:元组是不可变对象,其能不能作为字典的键呢?

    只有满足一定条件的元组,可以作为字典的键。

    如果元组中只包含字符串、数字等不可变对象,那么才能够作为字典的键;如果元组中直接或间接的包含了可变对象,那么就不能够作为字典的键。

    >>> dict1 = {(1, "hi", (), True): "abc"}
    >>>
    >>> dict2 = {(1, "hi", [], True): "abc"}  # 元组中包含有列表
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    

    访问字典中的值

    在字典中,我们需要通过字典的键来访问其对应的值。

    • 通过 dict[key] 取值
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1["name"]  # 取 key = "name" 的值
    'wintest'
    >>> dict1["age"]  # 取 key = "age" 的值
    13
    >>>
    >>> dict1["xxx"]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'xxx'
    

    如果键不存在,那么取值时就会报错:KeyError: 'xxx'

    • 通过 get(key) 取值
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1.get("name")
    'wintest'
    >>> dict1.get("age")
    13
    >>>
    >>> dict1.get("xxx")
    >>>
    >>> print(dict1.get("xxx"))
    None
    >>>
    

    如果键不存在,那么取值时会返回 None ,并不会报错,这种情况下我们也可以让其返回一个指定的值,该操作并不会影响字典的键值。如下:

    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1.get("name", "123")  # 键存在时直接返回对应的值
    'wintest'
    >>> dict1.get("xxx", "123")  # 键不存在时返回指定的值
    '123'
    >>>
    >>> dict1
    {'name': 'wintest', 'age': 13}
    

    更新字典

    • 通过 dict[key] 修改字典

    在字典中,我们可以通过字典的键 dict[key] 来修改其对应值,如果键不存在,那么就会把该键值对添加到字典中。

    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1["xxx"] = "123"  # 添加键值对
    >>>
    >>> dict1
    {'name': 'wintest', 'age': 13, 'xxx': '123'}
    >>>
    >>> dict1["age"] = 66  # 修改键的对应值
    >>>
    >>> dict1
    {'name': 'wintest', 'age': 66, 'xxx': '123'}
    

    在上面我们提到,字典中的键必须是唯一的,如果在创建字典时对同一个键赋值多次,那么只有最后一个值会被记住,因为对同一个键多次赋值时,其实就相当于 dict[key] 对字典进行修改。

    • 通过 update(dict) 修改字典

    字典中的 update() 方法,传入参数需要是一个新字典,该操作会把新字典中的键值对更新到原字典中。

    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict2 = {"name": "hihihi", "sex": "女"}
    >>>
    >>> dict1.update(dict2)  # 把 dict2 中键值对,更新到 dict1 中
    >>>
    >>> dict1
    {'name': 'hihihi', 'age': 13, 'sex': '女'}
    

    删除字典元素

    • 通过 del 删除字典中的键值对
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> del dict1["name"]
    >>>
    >>> dict1
    {'age': 13}
    >>>
    >>> del dict1["name"]  # 如果键不存在会报错
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'name'
    
    • 通过 pop() 删除字典中的键值对
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1.pop("name")
    'wintest'
    >>>
    >>> dict1
    {'age': 13}
    >>>
    

    使用 pop() 方法有一个好处,如果要删除的键值对不存在,那么就可以设置指定返回值来避免出现报错,如下:

    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1.pop("xxx")  # 键不存在,没有指定返回值
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'xxx'
    >>>
    >>> dict1.pop("xxx", "不存在的key")  # 键不存在,指定返回值
    '不存在的key'
    
    • 通过 del 删除整个字典
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> del dict1  # 删除字典
    >>>
    >>> dict1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'dict1' is not defined
    
    • 通过 clear 清空字典
    >>> dict1 = {"name": "wintest", "age": 13}
    >>>
    >>> dict1.clear()
    >>>
    >>> dict1
    {}
    

    字典的遍历

    字典在遍历时,也可以类似列表、集合等数据类型,通过关键字 in 来实现。

    dict1 = {"name": "wintest", "age": 13}
    
    for key in dict1:
        print(key, dict1[key])
    

    上面对字典遍历时,只会对字典的键进行遍历,需通过键去手动获取其对应的值,因此,当我们判断某元素是否在字典中时(如 xxx in dict),其实是判断字典所有键中,是否包含有该元素。

    我们也可以使用 dict1.items() ,先以列表返回一个视图对象,然后对其遍历时,可以直接获取到字典中的键和值,如下:

    dict1 = {"name": "wintest", "age": 13}
    
    print(dict1.items())  # dict_items([('name', 'wintest'), ('age', 13)])
    
    for key, value in dict1.items():
        print(key, value)
    

    字典函数&方法

    函数 & 方法 描述
    len(dict) 返回字典中键值对的个数
    dict.get(key, default=None) 返回字典中键的对应值
    dict.update(dict2) 把字典dict2的键值对更新到dict里
    dict.pop(key) 删除字典中指定键,返回被删除键的对应值
    dict.clear() 清空字典
    dict.items() 返回字典中所有的键值对
    dict.keys() 返回字典中所有的键
    dict.values() 返回字典中所有键的对应值
    dict.copy() 复制字典,使用的是浅拷贝
  • 相关阅读:
    uva 147 Dollars
    hdu 2069 Coin Change(完全背包)
    hdu 1708 Fibonacci String
    hdu 1568 Fibonacci
    hdu 1316 How Many Fibs?
    poj 1958 Strange Towers of Hanoi
    poj 3601Tower of Hanoi
    poj 3572 Hanoi Tower
    poj 1920 Towers of Hanoi
    筛选法——素数打表
  • 原文地址:https://www.cnblogs.com/wintest/p/16062435.html
Copyright © 2020-2023  润新知