字典(Dictionary)
语法:{ }(无序、可变,且键 Key 必须是唯一且不可变的)
# 空字典
a = {}
b = dict()
标准字典格式:
dict = {
"name": "Alice",
"age": 25,
"is_student": True
}
访问元素
d = {"name": "Alice", "age": 25}
d.get("name") # "Alice"
添加新键值对
d["city"] = "Beijing"
# {"name": "Alice", "age": 25, "city": "Beijing"}
修改已有键的值
d["age"] = 26
# {"name": "Alice", "age": 26}
update 方法:批量添加/更新
d.update({"age": 27, "gender": "female"})
# {"name": "Alice", "age": 27, "gender": "female"}
删除元素
pop(删除并返回值)
d.pop("age") # 25,d 变为 {"name": "Alice"}
清空字典
d.clear() # {}
集合(set)
Python 集合(set)是一种无序、不重复的可变容器,语法上使用花括号 {}
#空集合
a=set() 只有这一个表示方法
增加元素
s={1,2,3}
s.add(4) #{1, 2, 3, 4} 添加一个元素
s.update(4,5) #{1, 2, 3, 4,5} 添加多个元素
删除元素
s = {1, 2, 3, 4, 5}
s.remove(3) # 删除指定元素 → {1, 2, 4, 5}
s.pop() # 随机弹出一个元素并返回(集合无序)
s.clear() # 清空集合 → set()
集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
并集
a.union(b) # {1, 2, 3, 4, 5, 6}
交集
a.intersection(b) # {3, 4}
差集
a.difference(b) # {1, 2} 在a中但不在b中