字典概念
字典是 Python 提供的一種常用的數據結構,它用于存放具有映射關系的數據。為了保存具有映射關系的數據,Python 提供了字典,字典相當于保存了兩組數據,其中一組數據是關鍵數據,被稱為 key;另一組數據可通過 key 來訪問,被稱為 value
語法:
注意事項:
鍵值對,類似Java的Set
題目:
字典的鍵不能改變,所以可以使用元組當鍵值,而不能使用列表當鍵值
增加字典
刪除字典
del與popitem一樣,刪除一個元素,返回被刪除這個元素的 key-value
修改字典
查找字典
直接查找
使用get()函數查找字典
題目:
get(“a”,“b”):a是鍵,b是值;如果想要查找的鍵所對應的值不存在,則輸出字典中鍵所對應的值
合并兩個字典-update()函數
遍歷字典
1.for循環
2.keys()遍歷
3.values()遍歷
4.items()遍歷
遍歷字典-sorted()和Set()函數
按順序遍歷所有鍵
要以特定順序返回元素,我們可以使用 sorted() 函數來獲得按特定順序排列的鍵列表副本。
sort 與 sorted 區別:
sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。
list 的 sort 方法返回的是對已經存在的列表進行操作,無返回值,而內建函數 sorted 方法返回的是一個新的list,而不是在原來的基礎上進行的操作。
for name in sorted(dict2.keys()):print(name.title())
當值中含有很多重復值時,為了剔除重復項,可使用集合 set()
for name in set(dict2.values()):print(name.title())
字典推導式
字典嵌套
將字典儲存在列表中,或者將列表儲存在字典中,稱為嵌套。
字典列表
dict1 = {'物理':90,'化學':85,'生物':88}
dict2 = {'物理':95,'化學':88,'生物':70}
dict3 = {'物理':80,'化學':90,'生物':75}
dict4 = [dict1,dict2,dict3]
for a in dict4:print(a)
字典嵌套列表
dict5 = {'color':'blue','type':['A','B','C']
}
字典嵌套字典
dict6 = {'a':{'name':'Tom','age':6}'b':{'name':'Marry','age':10}
}
練習1-字典列表:用戶輸入姓名
# 讓用戶輸入姓名,
# 如果該姓名在 persons 中存在,提示用戶;
# 若不存在,繼續輸入年齡到列表中。
persons = [{'name': 'Tom', 'age': 18},{'name': 'lisa', 'age': 15},{'name': 'Sufv', 'age': 20},{'name': 'Linda', 'age': 13}
]
print(persons)
flag = True
while flag:name = input("請輸入姓名")for i in persons:if name == i["name"]:print("該姓名在 persons 中存在,結束循環")flag = Falsebreakelse:age = int(input("請輸入年齡"))check = {}check[name] = agepersons.append(check)break
print(persons)
練習3-字典列表輸出最高分和最低分對應的學生姓名
students = [{'name': '張三', 'age': 18, 'score': 88, 'tel': '1323454658', 'gender': '男'},{'name': '李四', 'age': 19, 'score': 89, 'tel': '1111454656', 'gender': '女'},{'name': 'jack', 'age': 38, 'score': 30, 'tel': '12142344562', 'gender': '不明'},{'name': '小白', 'age': 26, 'score': 35, 'tel': '12142345658', 'gender': '女'},{'name': '可文', 'age': 20, 'score': 90, 'tel': '1903334258', 'gender': '男'},{'name': 'mike', 'age': 14, 'score': 100, 'tel': '1345555678', 'gender': '女'},
]
max=students[0]["score"]
min=students[0]["score"]
maxStudent=''
minStudent=''for i in students:max = max if max > i["score"] else i['score']min = min if min < i["score"] else i['score']for j in range(len(students)):if max == students[j]["score"]:maxStudent = students[j]["name"]if min == students[j]["score"]:minStudent = students[j]["name"]print(max,min,maxStudent,minStudent,sep=' ')
綜合練習-字典列表:學生信息輸出
# 4
# 聲明一個列表,列表中包含6位學生的信息,
# 每位學生的信息包括:
# 姓名,年齡,分數(單科),電話,性別(男,女,不明)
students = [{'name': '張三', 'age': 18, 'score': 88, 'tel': '1323454658', 'gender': '男'},{'name': '李四', 'age': 19, 'score': 89, 'tel': '1111454656', 'gender': '女'},{'name': 'jack', 'age': 38, 'score': 30, 'tel': '12142344562', 'gender': '不明'},{'name': '小白', 'age': 26, 'score': 35, 'tel': '12142345658', 'gender': '女'},{'name': '可文', 'age': 20, 'score': 90, 'tel': '1903334258', 'gender': '男'},{'name': 'mike', 'age': 14, 'score': 100, 'tel': '1345555678', 'gender': '女'},
]
#(1)統計不及格學生個數;
count=0
for i in students:if i["score"]<60:count+=1
print("不及格學生人數:"+str(count))# (2)打印不及格學生姓名和對應成績;
count=0
list=[]
for i in students:if i["score"]<60:list.append(i["name"]+"的成績為"+str(i["score"]))
print("不及格學生信息:")
print(list)# (3)統計未成年學生個數;
count=0
for i in students:if i["age"]<18:count+=1
print("未成年學生人數:"+str(count))# (4)打印手機尾號是8的學生名字;
print('手機尾號是8的學生名字:')
for i in students:if i["tel"].endswith('8')==True:print(i["name"])# (5)打印最高分和對應的學生的名字;
max=students[0]["score"]
maxStudent=''
for i in students:max = max if max > i["score"] else i['score']
for j in range(len(students)):if max == students[j]["score"]:maxStudent = students[j]["name"]print("最高分:"+str(max)+"對應的學生姓名為:",maxStudent)# #(6)刪除性別不明的所有學生;
j=0
print(students)
for i in students:if i["gender"]=='不明':students.pop(j)j += 1
print(students)# (7)將列表按學生成績從大到小排序。
#冒泡排序
print(students)
for i in range(len(students) - 1):for j in range(len(students) - 1 - i):if students[j]["age"] < students[j+1]["age"]:temp = students[j]students[j] = students[j + 1]students[j + 1] = tempprint(students)
實驗–評委分數
# (1) 輸入評委人數;
number=int(input('the number of judges:'))
while number<3:print('number is not quality')number=int(input('the number of judges:'))
# (2) 輸入每個評委打分,以字典的形式錄入(分數在0-100之間);
score={}
key=97
for i in range(number):s=int(input('the score of the judge:'))while s<0 or s>100:print('score is not quality')s = int(input('the score of the judge:'))score[chr(key + i)]=s
print(score)
# (3) 刪除最高分和最低分;
max_score=max(score.items(),key=lambda x:x[1])
min_score=min(score.items(),key=lambda x:x[1])
# print(max_score,min_score,sep='\n')score.pop(max_score[0])
score.pop(min_score[0])
print(score)
# (4) 計算剩余打分的平均分。
from functools import reduce
list1=list(score.values())
average=reduce(lambda x,y:x+y,list1)
print("the average score="+str(average/len(list1)))