数据结构之字典

本文详细介绍了Python字典的定义、初始化、访问、增加和修改、删除等操作,强调了字典遍历的各种方式,包括直接遍历、通过keys()、values()和items()等方法。还探讨了在遍历过程中如何删除和构建字典,特别是有序字典的构建,强调了OrderedDict在保持插入顺序上的作用。
摘要由CSDN通过智能技术生成

导文

字典类型的容器在编程中的重要性不再言谈,通过现有典型互联网企业及传统企业专门部署redis集群服务器可知字典的编程、业务应用方面的重要性。

字典定义及初始化

  • 非线性结构容器
  • key-value键值对的数据集合
  • 可变的,无须的,key不重复
  • key值必须可hash
1.If no positional argument is given, an empty dictionary is created
  当没有位置参数给定时,一个空的字典被创建
2.If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object.
  当位置参数给定时,而且是一个映射对象,字典被创建,key-value是映射对象组
3.the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.
  当位置参数是可迭代对象时,每一个item必须有两个值,第一个值在字典中为key,第二个值在字典中为value
4.If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
  如果一个key重复出现,最后一个值覆盖之前的key值
  • class dict(**kwarg)
    此类方法构建字典时,通常采用name=value初始化一个字典,即key-value的映射,而此类方法要注意如下代码写法
#!/bin/python3
#-*- coding: UTF-8 -*-
#忌讳dict("a"=1,"b"=2),因为字符串对象不能接受赋值,而a=1,b=2才可以正常定义变量及赋值
dic = dict(a=1,b=2,c=3)
print(dic)
  • class dict(mapping,**kwarg)
    此类方法构建字典时,通常采用函数或其他关系映射为二元组的数据
#!/bin/python3
#-*- coding: UTF-8 -*-
dic = dict(zip(['one','two','three'],[1,2,3]))
print(dic)
  • class dict(iterable,**kwarg)
    此类方法是通过可迭代对象,可迭代对象必须为二元组,但是二元组中key值必须可hash
    错误代码示范:
#!/bin/python3
#-*- coding: UTF-8 -*-
#key值出现不可hash值
dic = dict([(["a","b"],10),("c",20)])
print(dic)
运行结果:
Traceback (most recent call last):
  File "./dic.py", line 4, in <module>
    dic = dict([(["a","b"],10),("c",20)])
TypeError: unhashable type: 'list'

正确代码示范࿱

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值