python爬虫
直播中

mushenmu

2年用户 732经验值
擅长:可编程逻辑
私信 关注
[经验]

python字典

python字典字典(英文名 dict),它是由一系列的键值(key-value)对组合而成的数据结构。
字典中的每个键都与一个值相关联,其中
键,必须是可 hash 的值,如字符串,数值等
值,则可以是任意对象
1. 创建字典创建一个字典有三种方法
第一种方法:先使用 dict() 创建空字典实例,再往实例中添加元素
  1. >>> profile = dict(name="张三", age=18)
  2. >>> profile
  3. {'name': '张三', 'age': 18}
第二种方法:直接使用 {} 定义字典,并填充元素。
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile
  3. {'name': '张三', 'age': 18}
第三种方法:使用 dict() 构造函数可以直接从键值对序列里创建字典。
  1. >>> info = [('name', '张三'), ('age', 18)]
  2. >>> dict(info)
  3. {'name': '张三', 'age': 18}
第四种方法:使用字典推导式,这一种对于新手来说可能会比较难以理解,我会放在后面专门进行讲解,这里先作了解,新手可直接跳过。
  1. >>> adict = {x: x**2 for x in (2, 4, 6)}
  2. >>> adict
  3. {2: 4, 4: 16, 6: 36}
2. 增删改查增删改查:是 新增元素、删除元素、修改元素、查看元素的简写。
由于,内容比较简单,让我们直接看演示
查看元素查看或者访问元素,直接使用 dict[key] 的方式就可以
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile["name"]
  3. '张三'
但这种方法,在 key 不存在时会报 KeyValue 的异常
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile["gender"]
  3. Traceback (most recent call last):
  4.   File "", line 1, in
  5. KeyError: 'gender'
所以更好的查看获取值的方法是使用 get() 函数,当不存在 gender 的key时,默认返回 male
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile.get("gender", "male")
  3. 'male'
新增元素新增元素,直接使用 dict[key] = value 就可以
  1. >>> profile = dict()
  2. >>> profile
  3. {}
  4. >>> profile["name"] = "张三"
  5. >>> profile["age"] = 18
  6. >>> profile
  7. {'name': '张三','age': 18}
修改元素修改元素,直接使用 dict[key] = new_value 就可以
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile["age"] = 28
  3. >>> profile
  4. {'name': '张三', 'age': 28}
删除元素删除元素,有三种方法
第一种方法:使用 pop 函数
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile.pop("age")
  3. 18
  4. >>> profile
  5. {'name': '张三'}
第二种方法:使用 del 函数
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> del profile["age"]
  3. >>> profile
  4. {'name': '张三'}
3. 重要方法判断key是否存在在 Python 2 中的字典对象有一个 has_key 函数,可以用来判断一个 key 是否在该字典中
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> profile.has_key("name")
  3. True
  4. >>> profile.has_key("gender")
  5. False
但是这个方法在 Python 3 中已经取消了,原因是有一种更简单直观的方法,那就是使用 in 和 not in 来判断。
  1. >>> profile = {"name": "张三", "age": 18}
  2. >>> "name" in profile
  3. True
  4. >>> "gender" in profile
  5. False
设置默认值要给某个 key 设置默认值,最简单的方法
  1. profile = {"name": "张三", "age": 18}
  2. if "gender" not in profile:
  3.     profile["gender"] = "male"
实际上有个更简单的方法
  1. profile = {"name": "张三", "age": 18}
  2. profile.setdefault("gender", "male")

更多回帖

发帖
×
20
完善资料,
赚取积分