字典
1.什么是字典(dict)
字典是容器型数据类型(序列),将{ } 作为容器的标志,里面多个元素用 , 隔开
1)
特点:可变(支持增删改),无序(不支持下标操作)
2)字典中的元素
字典中的元素都是键值对,以 键:值 的形式成对出现 - {key1:value1, key2:value2,...}
字典存储数据主要为了存储值,键只是为了区分不同的值而存在的
键值对中的键 - 不可变;唯一的
键值对中的值 - 任何数据类型都可以作为值(和列表元素一样)
list1 = {'x': 2, 'y': [123, 5], (1, 2): 'abba'}
print(list1)
# list1 = {'x': 2, 'y': [123, 5], [1, 2]: 'abba'} # TypeError: unhashable type: 'list'
# print(list1)
# key是唯一的
list1 = {'x': 2, 'x': 7} # 相同的 key 值 只保存最后一个
print(list1) # {'x': 7}
class1 = {
'name': 'zz',
'add': 'xx',
'head_teacher': {
'name': 'ss',
'tel': '11111111',
'qq': '2222222'
},
'students': [
{
'name': 'qqw',
'gender': '男',
'id': '23132564865'
},
{
'name': 'aqw',
'gender': '男',
'id': '23132564822'
}
]
}
2.查 - 获取字典的值
1)获取单个元素的值
字典[key] - 获取字典中指定key对应的值(value)
字典.get(key) / 字典.get(key,默认值) - 获取字典中指定key对应的值;如果key不存在返回None或者默认值(是否写入了默认值)
dog = {'name': 'dd', 'age': 3, 'type': '中华田园', 'color': '灰色', 'gender': '母'}
print(dog['name'], dog['gender'])
# print(dog['weight']) # KeyError: 'weight'
print(dog.get('age'), dog.get('color'))
# weight 不存在
print(dog.get('weight')) # None
print(dog.get('weight', 'sssss')) # sssss
2)获取多个元素的值(遍历)
遍历字典直接取到的是键(key)
for key in 字典:
pass
for value in dog.values():
pass
for key,value in dag.items():
pass
常见的遍历方式
dog = {'name': 'dd', 'age': 3, 'type': '中华田园', 'color': '灰色', 'gender': '母'}
2.1)
print("---------------------")
for key in dog:
print(key) # 取出key
print(dog[key]) # 取出值
pass
print("---------------------")
2.2)
for value in dog.values():
print(value)
pass
print("---------------------")
2.3)
print(dog.items())
for key, value in dog.items():
print(key, value)
pass
print("---------------------")
3.增和改
增 - 添加键值对;
改 - 修改字典中某个key对应的值
语法: 字典[key] = 值 - 当 key 不在字典中,添加进入字典相应的键值对;当 key 在字典中,修改对应的键值对中的值
增
dict2 = {'a': 1, 'b': 2}
print(dict2)
dict2['c'] = 3
print(dict2)
改
dict2['a'] = 100
print(dict2)
4.删 - 删除 key 对应的值
1)del 字典[key] - 删除字典中对应 key 的键值对
2)字典.pop(key) - 取出字典中 key 对应的值;返回被取出来的值
dict2 = {'a': 100, 'b': 2, 'c': 3}
del dict2['a']
print(dict2)
dict2 = {'a': 100, 'b': 2, 'c': 3}
value = dict2.pop('a')
print(dict2)
print(value)
5.相关运算
# print({'a': 10} + {'b': 20}) # TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
import dic as dic
字典不支持 + * > >= < <=
支持; == !=
print({'a': 10, 'b': 20} == {'a': 10, 'b': 20}) # True
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) # True
6.相关操作:in / not in
key in 字典 - 判断字典中是否存在某个键
max 、 min 、 sum - 针对的是 key 的操作
dict(数据) - 将指定的数据转换成字典
数据的要求:
1)数据本身就是一个序列
2)序列中的元素必须是有且只有两个元素的小序列 [[元素11, 元素12], (元素21, 元素22)]
print(2 in {'a': 10, 'b': 20}) # False
print('a' in {'a': 10, 'b': 20}) # True
dict1 = {'a': 1, 'b': 2, 'c': 3, 'z': 1}
print(max(dict1)) # 判断 key 的大小 z
print(min(dict1)) # a
dict2 = {10: 11, 20: 21, 30: 31}
print(sum(dict2)) # 60 键相加
print(len(dict2))
# print(dict([[1, 2], (1, 2), 'a']))
7.相关方法
字典.clear()
dict1 = {'NAME': 'Tony', 'AGE': 18, 'gender': '男',
'chinese': 89, 'math': 90, 'height': 180, 'weight': 67}
dict1.clear()
print(dict1)
dict.fromkeys(序列, 值1 = None) - 创建一个新的字典,将序列中的元素作为字典的key,将之1作为每隔个key对应的value
new_dict = dict.fromkeys('abc')
print(new_dict) # {'a': None, 'b': None, 'c': None}
new_dict = dict.fromkeys(range(10, 16), 100)
print(new_dict) # {10: 100, 11: 100, 12: 100, 13: 100, 14: 100, 15: 100}
2)字典.items() - 将字典中的键值对转换成元祖作为容器中的元素
dict1 = {'NAME': 'Tony', 'AGE': 18, 'gender': '男',
'chinese': 89, 'math': 90, 'height': 180, 'weight': 67}
print(dict1.items()) # dict_items([('NAME', 'Tony'), ('AGE', 18), ('gender', '男'), ('chinese', 89), ('math', 90), ('height', 180), ('weight', 67)])
3)字典.values(),字典.keys()
print(dict1.values(),dict1.keys()) # dict_values(['Tony', 18, '男', 89, 90, 180, 67]) dict_keys(['NAME', 'AGE', 'gender', 'chinese', 'math', 'height', 'weight'])
4)字典.setdefault(key, value = None) - 在字典中添加键值对(key 存在的时候不会有修改作用)
dict1.setdefault('long', 180)
print(dict1) # {'NAME': 'Tony', 'AGE': 18, 'gender': '男', 'chinese': 89, 'math': 90, 'height': 180, 'weight': 67, 'long': 180}
dict1.setdefault('heigt', 180)
print(dict1)
5) 字典1.update(字典2) - 讲字典2中的键值对全部添加到字典1中(相同的会后面加的覆盖前面的值)
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'x': 100, 'y': 200, 'c': 300}
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 2, 'c': 300, 'x': 100, 'y': 200}
dict1.update([(2, 3), (4, 5)])
print(dict1) # {'a': 1, 'b': 2, 'c': 300, 'x': 100, 'y': 200, 2: 3, 4: 5}
练习:用一个列表保存五只狗的信息,每只狗有:名字、年龄、颜色和体重
1)求5只狗的平均年龄 2)找到五只狗体重最大的狗的名字
list_dog = [
{'name': 'aa', 'age': 2, 'color': 'write', 'weight': 20},
{'name': 'bb', 'age': 5, 'color': 'write', 'weight': 32},
{'name': 'cc', 'age': 4, 'color': 'write', 'weight': 34},
{'name': 'dd', 'age': 7, 'color': 'write', 'weight': 33},
{'name': 'ee', 'age': 3, 'color': 'write', 'weight': 35}
]
max_weight = list_dog[0]['weight']
sum_age = 0
for i in range(len(list_dog)):
sum_age += list_dog[i]['age']
pass
ave_age = sum_age / len(list_dog)
print(ave_age)
for i in range(len(list_dog)):
for j in range(len(list_dog)):
if list_dog[j]['weight'] > list_dog[i]['weight']:
print(list_dog[j]['name'])
break
集合
1.什么是集合(set)
集合是容器型数据类型(序列);将{ }作为容器的标志,多个元素用 , 隔开(和字典不一样,集合的元素是独立的数据不是键值对)
特点:可变(增删)、无序(不支持下标操作)
注意:{}表示空字典
元素 - 不可变数据;同一个元素只能有一个(唯一性)
set1 = {}
print(type(set1)) # <class 'dict'>
set2 = set()
print(set2) # set()
集合中的元素不可变
# set2 = {'abc', [1, 2]} # TypeError: unhashable type: 'list'
# set3 = {{'a': '5'}, True} # TypeError: unhashable type: 'dict'
# a = 5
# set4 = {a, True, {4, 3}} # TypeError: unhashable type: 'set'
集合自带去重功能
set6 = {1, 2, 3, 5, 1, 1, 2}
print(set6) # {1, 2, 3, 5}
scores = [34, 90, 89, 23, 34, 89, 100, 99]
scores = list(set(scores))
print(scores) # [34, 99, 100, 23, 89, 90]
2.集合元素的增删改查
1)查 - 只支持遍历,不能单独获取具体某一个元素(遍历出的值无序)
names = {'ss', 'aa', 'bb', 'ee'}
for item in names:
print(item, end=' ') # ee bb aa ss
2)增
集合.add(元素) - 不会产生新集合,只修改原集合
集合.update(序列)- 将序列(不可变的)中的所有元素添加到原集合中
names.add('qq')
print(names) # {'aa', 'bb', 'ee', 'qq', 'ss'}
names.update({100, 200})
print(names) # {'aa', 'bb', 100, 200, 'ee', 'qq', 'ss'}
3) 删
集合.remove(元素) - 删除集合中指定的元素
names = {'ss', 'aa', 'bb', 'ee'}
names.remove('ss')
print(names) # {'bb', 'aa', 'ee'}
4) 改(集合不支持修改元素的操作)
3.集合的相关方法
1).集合的数学运算:
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
求并集 :集合1 | 集合2
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9}
求交集 : 集合1 & 集合2
print(set1 & set2) # {4, 5, 6}
求差集:集合1 - 集合2 (获取集合1中除集合2的部分)
print(set1 - set2) # {1, 2, 3}
print(set2 - set1) # {8, 9, 7}
对称差集:集合1 ^ 集合2 (两个集合的并集对两个集合的交集求差集)
print(set1 ^ set2) # {1, 2, 3, 7, 8, 9}
集合1 > 集合2 判断集合2是否包含于集合1(集合1包含集合2)
print(set2 > set1) # False
集合1 < 集合2 判断集合1是否包含于集合2(集合2包含集合1)
print(set2 > set1)
2)集合的方法
移除集合中的所有元素 clear()
set1 = {1, 2, 3, 4, 5, 6}
print(set1.clear()) # None
拷贝一个集合 copy()
set1 = {1, 2, 3, 4, 5, 6}
print(set1.copy()) # {1, 2, 3, 4, 5, 6}
difference() 返回多个集合的差集
set1 = set.difference({1, 2, 3, 4, 5, 6, 7}, {1, 2}, {6, 7})
print(set1) # {3, 4, 5}
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
set1 = {1, 2, 3, 4, 5, 6}
set2 = {5, 6, 7}
set1.difference_update(set2)
print(set1) # {1, 2, 3, 4}
discard() 删除集合中指定的元素 - 该方法不同于 remove() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits) # {'apple', 'cherry'}
intersection() 返回集合的交集
set1 = {1, 2, 3, 4, 5, 6}
set2 = {5, 6, 7}
z = set1.intersection(set2)
print(z) # {5, 6}
intersection_update() 返回集合的交集
intersection_update() 方法不同于 intersection() 方法,因为 intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素。
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.intersection_update(y)
print(x) # {'apple'}
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.isdisjoint(y)
print(z) # False
issubset() 判断指定集合是否为该方法参数集合的子集。
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z) # True
issuperset() 判断该方法的参数集合是否为指定集合的子集
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z) # True
pop() 随机移除元素
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits) # {'banana', 'apple'}
remove() 移除指定元素 (如果移除的元素不在原集合中会报错)
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # {'apple', 'cherry'}
symmetric_difference() 返回两个集合组成的新集合,但会移除两个集合的重复元素
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.symmetric_difference(y)
print(z) # {'google', 'banana', 'runoob', 'cherry'}
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.symmetric_difference_update(y)
print(x) # {'runoob', 'google', 'cherry', 'banana'}
union() 返回两个集合的并集
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.union(y)
print(z) # {'apple', 'google', 'runoob', 'cherry', 'banana'}