字典的概念 字典是存儲數據的一種方式,與列表和元祖來說更靈活。元祖的局限性:值是無序,不可變的列表的局限性:如果裡面想存儲一個人的名字對應的值時dy,年齡對應的是30。使用一個列表是不行的如下: 1 >>> t=[name="dy",age=30] 2 File "<stdin>", line 1 ...
字典的概念
字典是存儲數據的一種方式,與列表和元祖來說更靈活。
元祖的局限性:值是無序,不可變的
列表的局限性:如果裡面想存儲一個人的名字對應的值時dy,年齡對應的是30。使用一個列表是不行的如下:
1 >>> t=[name="dy",age=30] 2 File "<stdin>", line 1 3 t=[name="dy",age=30] 4 ^ 5 SyntaxError: invalid syntaxView Code
字典的使用方法:
字典是python中唯一的映射類型是無序的(哈希表)
字典對象時可變的(數字,字元串,元祖都是不可變;列表和字典是可變的)。
但是字典的鍵必須使用不可變對象,並且一個字典中可以使用不同類型的鍵值。
keys()或者vales()返回鍵列表或者值列表。
items()返回包含鍵值對的元祖。
常用操作:
索引
新增
刪除
鍵、值、鍵值對
迴圈
長度
常用的字典方法
1、len(),hash() (用於判斷某個對象是否可以做一個字典的鍵,非哈希類型報TypeError)
2、dict.clear():刪除字典中的所有元素。
3、dict.fromkeys(seq,val=None):以seq中的元素為鍵創建並返回一個字典,val為指定預設值。
4、dict.get(key,default=None):返回key的value,如果該鍵不存在返回default指定的值
5、dict.has_key(key):判斷字典中是否存在key,建議使用in或者not in代替。
6、dict.items():返回鍵值對元祖的列表。
7、dict.keys():返回字典中鍵的列表。
8、dict.iter*():interitems(),iterkeys(),itervalues()返回迭代子而不是列表。
9、dict.pop(key[,default]):同get(),區別是若key存在,刪除並返回dict[key],若不存在切default未指定值,拋出KeyError異常。
10、dict.setdefault(key,default=None):同set(),若key存在則返回其value,若key不存在,則dict[key]=default。
11、dict.update(dict2):將dict2中的鍵值對添加到字典dict中,如果有重覆覆蓋,原字典不存在的條目添加進。
12、dict.values():返回字典中所有值的列表。
13、del dict1['a']刪除字典中鍵值為a的元素。
14、dict1.pop('a')刪除並且返回鍵為'a'的元素。
15、dict1.clear()刪除字典所有元素。
16、del dict1刪除整個字典。
字典的練習:
1 arg = {'bakend': "www.oldboy.org", 2 'record': {'server': '100.1.7.9', 3 'weight': 20, 4 'maxconn': 30 5 } 6 } 7 8 id_db = { 9 "name": "u1", 10 "age": 20, 11 "sar": "M", 12 "sal": 1000 13 } 14 15 dic2 = { 16 "name": "dy", 17 "age": 40, 18 } 19 20 21 22 print(arg) 23 24 25 #增加 26 arg['record']['name'] = "127.0.0.1" 27 print('增加:',arg) 28 29 #修改 30 arg['record']['server'] = "127.0.0.1" 31 arg['record']['weight'] = 10 32 33 print('修改:',arg) 34 35 #刪除: 36 # arg['record'].pop('name') #刪除並且返回鍵為'name'的元素。 37 # arg.clear() #刪除字典所有元素。 38 # del id_db #刪除整個字典。 39 del id_db['sar'] #刪除字典中鍵值為sar的元素。 40 print('刪除:',arg) 41 print('刪除:',id_db) 42 43 44 45 #初始化一個新的列表:(儘量不要用,除非只有一層) 46 c = dict.fromkeys([6,7,8],["name",{"alex":"dongye"},444]) 47 print(c) 48 c[7][1]["name"] = "user1" 49 print(c) 50 註意有坑,所有的字典元素都會存在一個記憶體塊的指針中。 51 52 53 54 55 #獲取:(沒有不會報錯,只會返回none) 56 ret = arg.get('record') 57 print('獲取(無報錯):',ret) 58 ret1 = id_db.get('A4') 59 print('獲取(無報錯):',ret1) 60 61 62 #將info1的元素覆蓋掉info (存在就覆蓋,不存在就更新) 63 id_db.update(dic2) 64 print('存在就覆蓋,不存在就更新: ',id_db) 65 66 67 #字典裡面取值,如果有就返回,如果沒有就創建個新的。 68 arg.setdefault('record') 69 print('有就返回,沒有就創建', arg) 70 71 arg.setdefault('owner') 72 print('有就返回,沒有就創建', arg) 73 74 arg.setdefault('pwd',1234) 75 print('有就返回,沒有就創建', arg) 76 77 78 #for 迴圈: 79 #列印Key和valus 80 #大數據量的時候這樣寫: 81 for i in id_db: 82 print(i,id_db[i]) 83 84 85 #列印key和key下標: 86 for k,v in enumerate(info.keys(),1): 87 print("keys:",k,v)View Code
字典的源代碼:
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除內容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 淺拷貝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根據key獲取值,d是預設值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有項的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 項可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 獲取併在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 獲取併在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,則創建,如果存在,則返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有項,只是將內容保存至view對象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict字典源代碼練習