字典
1.什么是字典(dict)
字典是容器型數(shù)據(jù)類型(序列)版姑,將{ } 作為容器的標(biāo)志讨韭,里面多個元素用 , 隔開
1)
特點(diǎn):可變(支持增刪改)脂信,無序(不支持下標(biāo)操作)
2)字典中的元素
字典中的元素都是鍵值對,以 鍵:值 的形式成對出現(xiàn) - {key1:value1, key2:value2,...}
字典存儲數(shù)據(jù)主要為了存儲值透硝,鍵只是為了區(qū)分不同的值而存在的
鍵值對中的鍵 - 不可變狰闪;唯一的
鍵值對中的值 - 任何數(shù)據(jù)類型都可以作為值(和列表元素一樣)
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對應(yīng)的值(value)
字典.get(key) / 字典.get(key,默認(rèn)值) - 獲取字典中指定key對應(yīng)的值;如果key不存在返回None或者默認(rèn)值(是否寫入了默認(rèn)值)
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對應(yīng)的值
語法: 字典[key] = 值 - 當(dāng) key 不在字典中濒生,添加進(jìn)入字典相應(yīng)的鍵值對埋泵;當(dāng) key 在字典中,修改對應(yīng)的鍵值對中的值
增
dict2 = {'a': 1, 'b': 2}
print(dict2)
dict2['c'] = 3
print(dict2)
改
dict2['a'] = 100
print(dict2)
4.刪 - 刪除 key 對應(yīng)的值
1)del 字典[key] - 刪除字典中對應(yīng) key 的鍵值對
2)字典.pop(key) - 取出字典中 key 對應(yīng)的值;返回被取出來的值
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.相關(guān)運(yùn)算
# 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.相關(guān)操作:in / not in
key in 字典 - 判斷字典中是否存在某個鍵
max 丽声、 min 礁蔗、 sum - 針對的是 key 的操作
dict(數(shù)據(jù)) - 將指定的數(shù)據(jù)轉(zhuǎn)換成字典
數(shù)據(jù)的要求:
1)數(shù)據(jù)本身就是一個序列
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.相關(guān)方法
字典.clear()
dict1 = {'NAME': 'Tony', 'AGE': 18, 'gender': '男',
'chinese': 89, 'math': 90, 'height': 180, 'weight': 67}
dict1.clear()
print(dict1)
dict.fromkeys(序列, 值1 = None) - 創(chuàng)建一個新的字典浴井,將序列中的元素作為字典的key,將之1作為每隔個key對應(yīng)的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() - 將字典中的鍵值對轉(zhuǎn)換成元祖作為容器中的元素
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}
練習(xí):用一個列表保存五只狗的信息霉撵,每只狗有:名字磺浙、年齡、顏色和體重
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)
集合是容器型數(shù)據(jù)類型(序列)徒坡;將{ }作為容器的標(biāo)志撕氧,多個元素用 , 隔開(和字典不一樣,集合的元素是獨(dú)立的數(shù)據(jù)不是鍵值對)
特點(diǎn):可變(增刪)喇完、無序(不支持下標(biāo)操作)
注意:{}表示空字典
元素 - 不可變數(shù)據(jù)伦泥;同一個元素只能有一個(唯一性)
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)查 - 只支持遍歷,不能單獨(dú)獲取具體某一個元素(遍歷出的值無序)
names = {'ss', 'aa', 'bb', 'ee'}
for item in names:
print(item, end=' ') # ee bb aa ss
2)增
集合.add(元素) - 不會產(chǎn)生新集合何暮,只修改原集合
集合.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.集合的相關(guān)方法
1).集合的數(shù)學(xué)運(yùn)算:
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() 方法海洼,因?yàn)?remove() 方法在移除一個不存在的元素時會發(fā)生錯誤跨新,而 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() 方法坏逢,因?yàn)?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() 判斷指定集合是否為該方法參數(shù)集合的子集。
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z) # True
issuperset() 判斷該方法的參數(shù)集合是否為指定集合的子集
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z) # True
pop() 隨機(jī)移除元素
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits) # {'banana', 'apple'}
remove() 移除指定元素 (如果移除的元素不在原集合中會報(bào)錯)
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # {'apple', 'cherry'}
symmetric_difference() 返回兩個集合組成的新集合浮入,但會移除兩個集合的重復(fù)元素
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.symmetric_difference(y)
print(z) # {'google', 'banana', 'runoob', 'cherry'}
symmetric_difference_update() 移除當(dāng)前集合中在另外一個指定集合相同的元素龙优,并將另外一個指定集合中不同的元素插入到當(dāng)前集合中。
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'}