Python 字典 — dict

水深无声 2022-09-03 10:23 502阅读 0赞

字典的定义

  • dict(字典) 是 除列表以外 Python 之中 最灵活 的数据类型
  • 字典同样可以用来 存储多个数据

    • 通常用于存储 描述一个 物体 的相关信息
  • 和列表的区别

    • 列表有序 的对象集合
    • 字典无序 的对象集合
  • 字典用 {} 定义 或者 dict()
  • 字典使用 键值对 存储数据,键值对之间使用 , 分隔

    • key 是索引
    • value 是数据
    • 之间使用 : 分隔
    • 键必须是唯一的
    • 可以取任何数据类型,但 只能使用 字符串数字元组
  1. xiaoming = {
  2. "name": "小明",
  3. "age": 18,
  4. "gender": True,
  5. "height": 1.75
  6. }

字典示意图

字典常用操作

  • IPython 中定义一个 字典,例如:goods_dict= {}
  • 输入 goods_dict. 按下 TAB 键,IPython 会提示 字典 能够使用的方法如下:

字典常用方法

各方法的用处,在上图中已说明了,这里选几个常用方法/操作测验一下。

字典定义

  1. In [81]: # 空字典定义
  2. In [82]: goods_dict = { }
  3. In [83]: goods_dict2 = dict()
  4. In [84]: type(goods_dict)
  5. Out[84]: dict
  6. In [85]: type(goods_dict2)
  7. Out[85]: dict
  8. In [86]: # 带有数据的字典定义
  9. ^
  10. In [88]: goods_dict ={ 'name': '掘金T恤', 'price': 59}
  11. In [89]: goods_dict2 = dict(name='掘金T恤', price=59)
  12. In [90]: type(goods_dict), type(goods_dict2)
  13. Out[90]: (dict, dict)
  14. In [91]: goods_dict
  15. Out[91]: { 'name': '掘金T恤', 'price': 59}
  16. In [92]: goods_dict2
  17. Out[92]: { 'name': '掘金T恤', 'price': 59}

字典添加数据

  1. In [94]: goods_dict
  2. Out[94]: { 'name': '掘金T恤', 'price': 59}
  3. In [95]: # 添加数据
  4. In [96]: goods_dict['size'] = 'L'
  5. In [97]: goods_dict
  6. Out[97]: { 'name': '掘金T恤', 'price': 59, 'size': 'L'}

字典删除数据

  1. In [102]: goods_dict
  2. Out[102]: { 'name': '掘金T恤', 'price': 59, 'size': 'L'}
  3. In [103]: # 删除指定键数据
  4. In [104]: del goods_dict['size']
  5. In [105]: goods_dict
  6. Out[105]: { 'name': '掘金T恤', 'price': 59}
  7. In [106]: goods_dict.pop('price')
  8. Out[106]: 59
  9. In [107]: goods_dict
  10. Out[107]: { 'name': '掘金T恤'}
  11. In [108]: goods_dict.popitem()
  12. Out[108]: ('name', '掘金T恤')
  13. In [109]: goods_dict
  14. Out[109]: { }

del goods_dict[key]、goods_dict.pop(key) 都是指定键key,删除字典内的键值对。

  • del 没有返回值,pop() 返回当前删除键的

goods_dict.popitem() 则是随机删除字典内一个键值对,并返回删除的键值对

  1. In [111]: goods_dict
  2. Out[111]: { 'name': '掘金T恤', 'price': 59}
  3. In [112]: # 清空字典数据
  4. In [113]: goods_dict.clear()
  5. In [114]: goods_dict
  6. Out[114]: { }

字典更新数据

  1. In [116]: goods_dict
  2. Out[116]: { 'name': '掘金T恤', 'price': 59}
  3. In [117]: # 更新字典数据
  4. In [118]: goods_dict['name'] = '掘金徽章'
  5. In [121]: goods_dict
  6. Out[121]: { 'name': '掘金徽章', 'price': 59}
  7. In [122]: goods_dict.setdefault('price', 18)
  8. Out[122]: 59
  9. In [123]: goods_dict
  10. Out[123]: { 'name': '掘金徽章', 'price': 59}
  11. In [124]: goods_dict.setdefault('size', 'M')
  12. Out[124]: 'M'
  13. In [125]: goods_dict
  14. Out[125]: { 'name': '掘金徽章', 'price': 59, 'size': 'M'}

可以发现字典中的 setdefault() 方法,当字典中已存在相对应的键时不会更新其键的值,只能用于增加键值对,而 字典[key] ,如果 key 存在则更新,不存在则新增。

  1. In [127]: goods_dict
  2. Out[127]: { 'name': '掘金徽章', 'price': 59, 'size': 'M'}
  3. In [128]: # 整体更新
  4. In [130]: new_info = { 'price': 18, 'size': '5cm'}
  5. In [131]: goods_dict.update(new_info)
  6. In [132]: goods_dict
  7. Out[132]: { 'name': '掘金徽章', 'price': 18, 'size': '5cm'}
  8. In [133]: new_info = { 'name': '掘金小册xx', 'author': 'hui', 'price': 19.9}
  9. In [134]: goods_dict.update(new_info)
  10. In [135]: goods_dict
  11. Out[135]: { 'name': '掘金小册xx', 'price': 19.9, 'size': '5cm', 'author': 'hui'}

字典中的 update(新字典) 方法则是将新字典中合并到原字典中。有相同的键则更新,没有的键则新增。

字典获取指定键的值

  1. In [137]: goods_dict
  2. Out[137]: { 'name': '掘金小册xx', 'price': 19.9, 'size': '5cm', 'author': 'hui'}
  3. In [138]: # 获取指定键的值
  4. In [139]: goods_dict['name']
  5. Out[139]: '掘金小册xx'
  6. In [140]: goods_dict['author']
  7. Out[140]: 'hui'
  8. In [141]: goods_dict.get('price')
  9. Out[141]: 19.9
  10. In [142]: goods_dict['id']
  11. ---------------------------------------------------------------------------
  12. KeyError Traceback (most recent call last)
  13. <ipython-input-142-b8a93fe9ad6b> in <module>
  14. ----> 1 goods_dict['id']
  15. KeyError: 'id'
  16. In [145]: ret = goods_dict.get('id')
  17. In [147]: print(ret)
  18. None
  19. In [148]: count = goods_dict.get('count', 0)
  20. In [149]: count
  21. Out[149]: 0

使用 字典[key] 当字典中的 key 不存在时会报错,字典.get(key) ,当键不存在时则默认返回 None,可以更改默认返回值,如 goods_dict.get('count', 0) ,获取商品数量当键不存在时默认为0.

其他

  1. In [154]: goods_dict
  2. Out[154]: { 'name': '掘金小册xx', 'price': 19.9, 'author': 'hui'}
  3. In [155]: # 字典中键值对的数量
  4. In [156]: len(goods_dict)
  5. Out[156]: 3
  6. In [157]: # 获取字典中的所有的 key
  7. In [158]: goods_dict.keys()
  8. Out[158]: dict_keys(['name', 'price', 'author'])
  9. In [161]: # 获取字典中的所有的 value
  10. In [162]: goods_dict.values()
  11. Out[162]: dict_values(['掘金小册xx', 19.9, 'hui'])
  12. In [163]: # 字典中所有的键值对(元组列表)
  13. In [164]: goods_dict.items()
  14. Out[164]: dict_items([('name', '掘金小册xx'), ('price', 19.9), ('author', 'hui')])

字典循环遍历

  • 遍历 就是 依次字典 中获取所有键值对

    In [167]: for key in goods_dict:

    1. ...: print('key', key)
    2. ...: print('value', goods_dict[key])
    3. ...: print()
    4. ...:
    5. ...:

    key name
    value 掘金小册xx

    key price
    value 19.9

    key author
    value hui

for ... in ... 默认取字典中的 keys() 所有的键 ,然后再通过键获取值。

然而我们可以通过字典中的 items() 来一次遍历键和值

  1. In [168]: for key, value in goods_dict.items():
  2. ...: print(key, value)
  3. ...: print()
  4. ...:
  5. ...:
  6. name 掘金小册xx
  7. price 19.9
  8. author hui

应用场景

  • 尽管可以使用 for in 遍历 字典
  • 但是在开发中,更多的应用场景是:

    • 使用 多个键值对,存储 描述一个 物体 的相关信息 —— 描述更复杂的数据信息
    • 多个字典 放在 一个列表 中,再进行遍历,在循环体内部针对每一个字典进行 相同的处理

    info_list = [

    1. {
    2. "name": "hui",
    3. "qq": "222815",
    4. "phone": "10010"
    5. },
    6. {
    7. "name": "zack",
    8. "qq": "54321",
    9. "phone": "10086"
    10. },
    11. {
    12. "name": "wang",
    13. "qq": "12345",
    14. "phone": "10000"
    15. }

    ]

尾语

✍ 用 Code 谱写世界,让生活更有趣。❤️

✍ 万水千山总是情,点赞再走行不行。❤️

✍ 码字不易,还望各位大侠多多支持。❤️

018.jpg

发表评论

表情:
评论列表 (有 0 条评论,502人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pythondict字典

    字典是一系列由键(key)和值(value)配对组成的元素的集合,在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个implementation

    相关 字典(dict)

    字典创建 赋值创建字典 通过工厂函数创建字典 通过字典的 fromkeys 方法创建字典 赋值创建字典 , key-value , 键值对 ![