定义
1. 字典是无序对象的集合。
2. 字典用花括号{}
定义。
3. 字典中键值(key => value)
对用冒号:
分隔,每个对中间用,
分隔。
- 键
key
是索引 - 值
value
是数据 - 键必须是唯一的
- 键必须是不可变的,如字符串、数字或元组
- 值可以是任意类型对象
例如:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
访问字典里的值
把相应的键放入到方括号中,若访问字典中不存在的键,则会报错实例:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
print("name:", people["name"])
print("age:", people["age"])
print("male", people["male"])
以上代码的运行结果为:
name: xiaoming
age: 18
male: True
Traceback (most recent call last):
File "demo.py", line 9, in <module>
print("height", people["height"])
KeyError: 'height'
修改字典
添加,修改字典元素,如下实例:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
people["height"] = 180 #添加元素
people["age"] = 19 #修改元素
print("height:", people["height"])
print("age:", people["age"])
以上代码的运行结果为:
height: 180
age: 19
删除字典元素
删除字典元素时可以删除一个元素,也可以清空字典中的全部元素
- 删除一个元素时,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
del people["name"] #删除单个元素
print(people)
- 输出结果为:
{'age': 18, 'male': True}
- 清空字典中的元素,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
people.clear() #清空字典元素
print(people)
- 输出结果为:
{}
- 也可以使用
del
删除整个字典,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
del people
print(people)
- 此时因为
people
该字典已经被删除,所以输出时会报错:
Traceback (most recent call last):
File "demo.py", line 7, in <module>
print(people)
NameError: name 'people' is not defined
字典键的特性
1. 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True,
"age": 19
}
print("age:", people["age"])
输出结果为:
age: 19
2. 键必须不可变,所以可以用数字、字符串或元组充当,而用列表就会报错,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True,
[1, 2, 3]: 123
}
print("[1, 2, 3]", people[[1, 2, 3]])
输出结果为:
Traceback (most recent call last):
File "demo.py", line 1, in <module>
people = {
TypeError: unhashable type: 'list'
字典内置函数&方法
- 字典包含了以下内置函数:
序号 | 函数 | 描述 |
1 |
| 计算字典元素个数,即键的总数 |
2 |
| 将字典变成字符串的形式 |
3 |
| 返回输入的变量类型,如果变量是字典就返回字典类型 |
以上三个内置函数的实列如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
peopleInfo = str(people) #str()函数
print(f"字典元素的个数为:{len(people)}") #len()函数
print(f"people为:{people},它的类型是{type(people)}") #type()函数
print(f"propleInfo为:{peopleInfo},它的类型是{type(peopleInfo)}")
输出结果为:
字典元素的个数为:3
people为:{'name': 'xiaoming', 'age': 18, 'male': True},它的类型是<class 'dict'>
propleInfo为:{'name': 'xiaoming', 'age': 18, 'male': True},它的类型是<class 'str'>
- 字典包含了以下内置方法:
序号 | 方法 | 描述 |
1 |
| 清空字典中所有元素 |
2 |
| 返回一个字典的浅复制 |
3 |
| 创建一个新字典,以元组
|
4 |
| 返回指定键的值,第二个参数为可选参数, 如果不存在默认返回 |
5 |
| 和get()类似, 第二个参数为可选参数, 如果键不存在,默认添加None,也可以自己设置default值 |
6 |
| 如果键在字典中就返回 |
7 |
| 以列表返回可遍历的(键, 值) 元组数组 |
8 |
| 返回一个迭代器,可以使用 list() 来转换为列表 |
9 |
| 返回一个迭代器,可以使用 |
10 |
| 把字典 |
11 |
| 删除字典给定键 key 所对应的值,返回值为被删除的值。 key值必须给出。 否则,返回default值 |
12 |
| 随机返回并删除字典中的最后一对键和 |
.clear()
方法,实例:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
print(f"people为:{people},元素个数为:{len(people)}")
people.clear()
print(f"people为:{people},元素个数为:{len(people)}")
输出结果为:
people为:{'name': 'xiaoming', 'age': 18, 'male': True},元素个数为:3
people为:{},元素个数为:0
.copy()
方法为浅拷贝,对于浅拷贝,我们有如下比较:
- 直接赋值:其实就是对象的引用(别名)
- 浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象
- 深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
这里仅比较直接赋值与浅拷贝,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
people1 = people #直接赋值
people2 = people.copy() #浅拷贝
people["name"] = "xiaohua" #修改原字典
print(people)
print(people1)
print(people2)
输出结果为:
{'name': 'xiaohua', 'age': 18, 'male': True}
{'name': 'xiaohua', 'age': 18, 'male': True}
{'name': 'xiaoming', 'age': 18, 'male': True}
fromkeys()
方法,实例如下:
seq = ("name", "age", "sex")
val = ("xiaoming", 18, True)
people = dict.fromkeys(seq)
print(people)
people = dict.fromkeys(seq, 10)
print(people)
输出结果为:
{'name': None, 'age': None, 'sex': None}
{'name': 10, 'age': 10, 'sex': 10}
.get()
和.setdefault
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
# .get()方法
name = people.get("name")
print(name)
height = people.get("height", 180)
print(people)
# .setdefault()方法
name1 = people.setdefault("name")
print(name1)
height1 = people.setdefault("height1", 185)
print(people)
输出结果为:
xiaoming
{'name': 'xiaoming', 'age': 18, 'male': True}
xiaoming
{'name': 'xiaoming', 'age': 18, 'male': True, 'height1': 185}
key in dict
方法应常用于if
语句中,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
if ("name" in people):
print(f"name是{people['name']}")
else:
print("键name不在people中")
if ("height" in people):
print(f"height是{people['height']}")
else:
print("键height不在people中")
输出结果为:
name是xiaoming
键height不在people中
.items()
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
print(people.items())
输出结果为:
dict_items([('name', 'xiaoming'), ('age', 18), ('male', True)])
.keys()
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
print(people.keys())
输出结果为:
dict_keys(['name', 'age', 'male'])
.values()
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
print(people.values())
输出结果为:
dict_values(['xiaoming', 18, True])
.update()
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
people1 = {
"name": "xiaoqiang",
"height": 180
}
people.update(people1)
print(people)
输出结果为:
{'name': 'xiaoqiang', 'age': 18, 'male': True, 'height': 180}
.pop(key[, default])
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18,
"male": True
}
name = people.pop("name")
print(people)
print(name)
height = people.pop("height", 180) #当要删除的键值不存在时,就会报错
print(people)
print(height)
输出结果为:
{'age': 18, 'male': True}
xiaoming
{'age': 18, 'male': True}
180
.popitem()
方法,实例如下:
people = {
"name": "xiaoming",
"age": 18
}
people.popitem()
print(people)
people.popitem()
print(people)
people.popitem() #需要注意当字典为空时,再删除就会报错
输出结果为:
{'name': 'xiaoming'}
{}
Traceback (most recent call last):
File "demo.py", line 9, in <module>
people.popitem()
KeyError: 'popitem(): dictionary is empty'