Python3.5 字典(Dictionary)
阿新 • • 發佈:2018-03-22
Python3.5 字典Python 字典
字典是另一種可變容器模型,且可存儲任意類型對象。
字典的每個鍵值 key=>value 對用冒號 : 分割,每個鍵值對之間用逗號 , 分割,整個字典包括在花括號 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2
鍵必須是唯一的,但值則不必。
值可以取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。
dic = {'name':'jin','age':18,'sex':'male'} print(dic)#{'name': 'jin', 'sex': 'male', 'age': 18}
####增####
#增 ##第一種:有則覆蓋,無則添加 # dic = {'name':'jin','age':18,'sex':'male'} # dic['hobby'] = 'girl' # print(dic) #輸出{'age': 18, 'hobby': 'girl', 'sex': 'male', 'name': 'jin'} # dic['name'] = 'wusir' # print(dic) #{'age': 18, 'sex': 'male', 'name': 'wusir'} # ##第二種:serdefult 無則添加,有則不變 dic = {'name':'jin','age':18,'sex':'male'} # dic.setdefault('hobby') # print(dic)#{'sex': 'male', 'hobby': None, 'age': 18, 'name': 'jin'} #'hobby'是鍵,而不是值,所以字典裏會出現'hobby':None # dic.setdefault('hobby','girl') # print(dic)#{'name': 'jin', 'hobby': 'girl', 'age': 18, 'sex': 'male'} #鍵值對 'hobby':girl添加到字典了、原字典沒有hobby # dic.setdefault('name','ritian') # print(dic)#{'age': 18, 'name': 'jin', 'sex': 'male'} #原字典中有k,name'所以不變
###刪####
#pop 有返回值 # dic = {'name':'jin','age':18,'sex':'male'} # print(dic.pop('age'))##返回所刪除鍵值對的age值18 # print(dic) # dic.pop('hobby')##報錯 # print(dic.pop('hobby',None))##設定返回的鍵值,當hobby不存在時,返回None ##clear 清空 # dic = {'name':'jin','age':18,'sex':'male'} # dic.clear() # print(dic)#{}清空字典裏面所有鍵值對 ##del # dic = {'name':'jin','age':18,'sex':'male'} # del dic # print(dic)#NameError: name 'dic' is not defined,通過del dic,已刪除字典dic # dic = {'name':'jin','age':18,'sex':'male'} # del dic['name'] # print(dic)#{'age': 18, 'sex': 'male'},刪除dic裏面‘name’的鍵值對 # dic = {'name':'jin','age':18,'sex':'male'} # print(dic.popitem()) # print(dic)#每次隨機刪除dic裏面的鍵值對
####改#####
# dic = {"name":"jin","age":18,"sex":"male"} # dic['name'] = '太白' # print(dic)#{'name': '太白', 'sex': 'male', 'age': 18}更改鍵name的值 # 兩個字典的改 # dic = {"name":"jin","age":18,"sex":"male"} # dic2 = {"name":"alex","weight":75} # dic2.update(dic)#將dic鍵值對,覆蓋並添加到dic2 # print(dic)#{'age': 18, 'name': 'jin', 'sex': 'male'} # print(dic2)#{'age': 18, 'sex': 'male', 'name': 'jin', 'weight': 75}
####查####
# dic = {"name":"jin","age":18,"sex":"male"} # print(dic['name'])#jin 查鍵所對應的值jin # print(dic['name1'])#KeyError: 'name1'如果查看沒有的鍵,則會顯示錯誤信息 # print(dic.get('name'))#jin # print(dic.get('name1'))#沒有此鍵時默認返回None # print(dic.get('name1','無此鍵值對'))#無此鍵值對,後面可以設置··· ##其它方法 #key() values() item() dic = {"name":"jin","age":18,"sex":"male"} # print(dic.keys(),type(dic.keys()))#查看dic的鍵keys # print(dic.keys())# # for i in dic.keys(): # print(i) #列出dic的所有鍵 # for i in dic: # print(i) # li = list(dic.keys())#以列表的形式查看dic鍵 # print(li) # print(dic.values())#值 # for i in dic.values():#列出dic的鍵值 # print(i) # #items 隨機打出dic的鍵值對 # print(dic.items())#打出dic的鍵值對,順序隨機 #dict_items([('age', 18), ('sex', 'male'), ('name', 'jin')]) # for i in dic.items():# # print(i,type(i)) # ('name', 'jin') <class 'tuple'> # ('sex', 'male') <class 'tuple'> # ('age', 18) <class 'tuple'>
Python3.5 字典(Dictionary)