字典 dictionary
新華字典 啊 a
概述:使用鍵-值(key-value)方式存儲(chǔ)。
'''
key的特點(diǎn):
1、字典中的key必須是唯一的
2、key值必須是不可變的數(shù)據(jù)類型:字符串、元組、Number
3、list是可變的,不能作為key值使用
value:可以是任意類型的數(shù)據(jù),可以重復(fù)。
字典的本質(zhì):一種無(wú)序的集合。
'''
思考:保存多位學(xué)生的姓名,性別,年齡,成績(jī)
保存多位學(xué)生的姓名及成績(jī)
lily 98 tom 67 lucy 98 hmm 45 lilei 45
使用字典:姓名:key 成績(jī):value
一、創(chuàng)建字典
格式: {key1:value1, key2:value2.....keyn:valuen}
lily 98 tom 67 lucy 98 hmm 45 lilei 45
# 1、創(chuàng)建一個(gè)帶有5個(gè)元素的字典
dic1 = {"Lily":98, "Tom":67, "Lucy":98, "Hmm":45, "Lilei":45}
print(dic1)
print(type(dic1)) # dict
# 2、創(chuàng)建一個(gè)空字典
dic2 = {}
print(dic2)
# 3、創(chuàng)建一個(gè)只有一個(gè)元素的字典
dic3 = {"a" : "abc"}
print(dic3)
# 4、驗(yàn)證key的規(guī)則
# 4.1、驗(yàn)證字符串是否可以作為key
dic4 = {"abc":1}
print(dic4)
# 4.2、驗(yàn)證Number是否可以作為key
dic5 = {1:"a"}
print(dic5)
# 4.3、驗(yàn)證Tuple是否可以作為key
dic6 = {(1,1):"abc"}
print(dic6)
# 4.4、驗(yàn)證List是否可以作為key 不允許
# dic7 = {[1,2]:"abc"} # TypeError: unhashable type: 'list'
# print(dic7)
# 4.5、驗(yàn)證key值是否可以重復(fù), 只會(huì)保留一次不同的key值
dic8 = {"a":1,"b":2, "a":3}
print(dic8)
二、字典的訪問(wèn)
# 1、獲取某一個(gè)元素方式1:字典名[key]
dic9 = {"tom":88, "ll":66, "hmm":77}
print(dic9["ll"])
# print(dic9["HH"]) # KeyError: 'HH' 當(dāng)前key不存在
# 2、獲取某一個(gè)元素方式2:字典名.get(key)
print(dic9.get("hmm"))
# get獲取字典中的值,如果當(dāng)前key值不存在,返回None
print(dic9.get("HH")) # None
if dic9.get("AA") == None:
print("當(dāng)前未保存姓名")
else:
print(dic9.get("AA"))
三、字典的操作
dic10 = {"Tom": 98, "Lily":89, "Lucy": 66}
print(dic10)
# 1、增 格式: 字典名[新的key]=value
dic10["Lilei"] = 100
print(dic10)
# 2、刪 : 將key值移除,對(duì)應(yīng)的value會(huì)自動(dòng)移除 pop
dic10.pop("Tom")
print(dic10)
# 3、改
dic10["Lily"] = 200
print(dic10)
# 4、查
print(dic10["Lily"])
四、遍歷字典
dic11 = {"Tom": 98, "Lily":89, "Lucy": 66}
# 1、遍歷字典
for key in dic11:
print(key, dic11[key])
# 2、字典名.keys():返回一個(gè)包含所有key的列表
print(dic11.keys())
for key in dic11.keys():
print(key)
# 3、字典名.values():返回一個(gè)包含所有value的列表
print(dic11.values())
for v in dic11.values():
print(v)
# 4、字典名.items():返回一個(gè)包含所有key-value的元組的列表
print(dic11.items()) # [('Tom', 98), ('Lily', 89), ('Lucy', 66)]
for key in dic11.items():
print(key)
# 字典元素的獲?。嚎梢灾苯颖闅vitems,分別獲取key及value
for key,value in dic11.items():
print(key, value)
dict與list相比:
dict:1、查找及插入速度塊,不會(huì)隨著key及value的增加而變慢
2、需要占用的內(nèi)存大,內(nèi)存浪費(fèi)多
list:1、查找及插入速度會(huì)隨著數(shù)據(jù)的增加而變慢
2、需要占用的內(nèi)存小,內(nèi)存浪費(fèi)少
題目:
數(shù)出字符串中出現(xiàn)的單詞,及對(duì)應(yīng)單詞出現(xiàn)的次數(shù)
'''
I have a good friend her name is Li Hua
We are in the same class So it is natural for us
to become partners When we have group work we
will cooperate well One thing that I admire Li Hua
so much is her persistence Sometimes when the task
is too hard to finish and I want to give up but Li
inspires me to hang on and she believes that we will
get over the difficulty Indeed under her leadership
'''
a=[1,11,6,3,8,77,4,5,7]
for i in range(len(a)-1):
for j in range(i+1,len(a)):
if a[i]<a[j]:
a[i],a[j]=a[i],a[j]
else:
a[i],a[j]=a[j],a[i]
print(a)