字典是python中惟一的一個映射類型,以{}大括號括起來的鍵值對組成
字典中的key是惟一的,必須是可hash,不可變的數據類型
語法:{key1:value,key2:value}
#擴展:python
可哈希(不可變)的數據類型:int,str,tuple,bool
不可哈希(可變)的數據類型:list,dict,set
#先來看看dict字典的源碼寫了什麼,方法:按ctrl+鼠標左鍵點dictapi
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除內容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 淺拷貝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根據key獲取值,d是默認值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 全部項的列表形式 """ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 項可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 全部的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 獲取並在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 獲取並在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 若是key不存在,則建立,若是存在,則返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 全部的值 """ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 全部項,只是將內容保存至view對象中 """ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None dict
#演示什麼數據類型能做爲keyapp
# dic = {'name':'guoke','age':22} #字符串能夠爲鍵(key) # dic = {1:'a',2:'b',3:'c'} #數字能夠爲鍵 # dic = {True:'1',False:'2'} #布爾值能夠爲鍵 # dic = {(1,2,3):'abc'} #元組也能夠爲鍵 # dic = {[1,2,3]:'abc'} #列表不能爲鍵{key:vaule}
#2.1增長ide
#關鍵字 # 一、setdefault('鍵','值') # 二、變量['key'] = 'value'
#例子:ui
dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'} dic['湖南'] = '長沙' #新增,前面是key,後面是值 print(dic) #{'廣東': '廣州', '山東': '濟南', '海南': '三亞', '湖南': '長沙'} dic.setdefault('廣西','桂林') # 使用setdefault須要注意的是若是在字典中存在就不進行任何操做,不存在就進行添加 print(dic) #{'廣東': '廣州', '山東': '濟南', '海南': '三亞', '廣西': '桂林'}
#2.2刪除this
#關鍵字 1、pop() 二、del dic[''] # 三、clear() #清空 四、popitem #隨機刪除 五、要注意的是字典沒有remove這個刪除命令
#例子:spa
dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
ret = dic.pop('廣東') #經過key刪除,返回被刪除的value print(ret) #廣州 :能夠查看到的是經過key將值爲廣州刪除了 print(dic) #{'山東': '濟南', '海南': '三亞'} del dic['山東'] #要注意刪的時候只能是寫key,不能寫value刪 print(dic) #{'廣東': '廣州', '海南': '三亞'} dic.clear() #{} #清空 print(dic) #{} ret = dic.popitem() #隨機刪除,返回值 一個元組(key,value) print(ret) #('海南', '三亞') print(dic) #{'廣東': '廣州', '山東': '濟南'}
#2.3.修改3d
#關鍵字 一、dic['鍵'] = '值' 二、dic.update(dic1)
#例子:rest
dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'}
dic["廣東"] = '湖北' #須要注意的是前邊的修改是鍵key,而後等號後面修改的value值 print(dic) #{'廣東': '湖北', '山東': '濟南', '海南': '三亞'} dic1 = {'戰狼':'吳京','亮劍':'李雲龍','山東':'淮上'} dic.update(dic1) print(dic) #{'廣東': '湖北', '山東': '淮上', '海南': '三亞', '戰狼': '吳京', '亮劍': '李雲龍'} #把dic1中的內容更新到dic中,若是key重名,則修改替換,若是不存在key,則新增
#2.4.查詢code
# 關鍵字 # 一、使用for循環獲取,獲取到的是鍵,不是值 # 二、print(dic['']) #查詢鍵,返回值 # 三、print(dic.get('')) #若是沒有查詢到的話就會返回None # 四、print(dic.setdefault(''))
#例子:
dic = {'廣東':'廣州','山東':'濟南','海南':'三亞'} # for i in dic: # print(i) #for循環默認是獲取字典中的鍵 # 廣東 # 山東 # 海南 print(dic['廣東']) #查看1,若是沒有這個鍵的時候查詢就會報錯 # print(dic['湖北']) #報錯,NameError: name '湖北' is not defined print(dic.get('廣東','這個是沒有的')) #查看2,沒有返回None,能夠指定返回內容 #廣州 print(dic.get('廣西')) #None,由於沒有這個key print(dic.setdefault('廣東')) #若是沒有的話也是返回None
#2.5.字典的其餘操做(特有)
#keys #獲取到字典中的每個鍵 #value #獲取到字典中的值 #itmes #獲取到字典中的鍵值對數據
#例子:
dic = {"id":123,"name":"cw","age":22,"ok":"大佬"} print(dic.keys()) #(高仿列表) for i in dic.keys(): print(i) #獲取到鍵:id,name,age,ok for i in dic: print(i) #以上的幾種方法都是獲取到字典中的每個鍵 #獲取到id,name,age,ok print(dic.values()) for i in dic.values(): #獲取到字典中的每個值 print(i) #獲取到值:123,cw,22,大佬 for i in dic.items(): #獲取到鍵值對 print(i) # ('id', 123) # ('name', 'cw') # ('age', 22) # ('ok', '大佬')
嵌套就是一層套着一層,字典套着字典
#演練:
#寫字典嵌套來查找 dic1 = { "name": "張世豪", "age": 18, "wife": { "name": '大哥成', "age": 28 }, "children": ['第⼀個毛孩子', '第⼆個毛孩子'], "desc": '峯哥不不會告我吧. 不要緊. 我想上頭條的' } #經過key取查找,使用get #1.查找大哥成 #思路:首先能夠看到大哥成是做爲wife鍵的值,因此能夠先找wife鍵,拿到值,再接着獲取鍵name,打印出它的value值 print(dic1.get("wife")) #{'name': '大哥成', 'age': 28} print(dic1.get("wife").get("name")) #大哥成 #2.查看28 #思路:和上面同樣,經過找出鍵獲取到值 print(dic1.get("wife").get("age")) #28 #3.查找第一個毛孩子 #思路:一樣是經過鍵找出值,而後經過索引進行獲取 print(dic1.get("children")[0]) #第⼀個毛孩子
#嵌套練習
dic1 = { 'name':['guo',2,3,5], 'job':'teacher', 'dianshi':{'haijun':['python1','python2',100]} } #要求 # 1,將name對應的列表追加⼀個元素’ke’。 # 2,將name對應的列表中的guo首字母大寫。 # 3,dianshi對應的字典加一個鍵值對’蔣小魚’,’niubi’。 # 4,將dianshi對應的字典中的haijun對應的列表中的python2刪除 # s1 = (dic1.get('name')) s1.append('ke') print(s1) #['guo', 2, 3, 5, 'ke'] print(dic1.get('name')[0].capitalize()) #Guo dic1['蔣小魚'] = 'niubi' print(dic1) #{'name': ['guo', 2, 3, 5], 'job': 'teacher', 'dianshi': {'huijun': ['python1', 'python2', 100]}, '蔣小魚': 'niubi'} dic2 = (dic1.get('dianshi').get('haijun').pop(1)) print(dic2) #python2 print(dic1) #{'name': ['guo', 2, 3, 5], 'job': 'teacher', 'dianshi': {'haijun': ['python1', 100]}}