字典Dictinary是一种无序可变容器,字典中键与值之间用“:”分隔,而与另一个键值对之间用","分隔,整个字典包含在{}内: dict1 = {key1:value1, key2:value2}
键必须是唯一的,而值不必,创建时如果同一个键被赋值两次,后一个值会被记住
键必须是不可变类型,如字符串,数字,元组(不能是列表),但值可以取任何类型,也可以是自定义类,比如: dict1 = {'k1':'v1', 1:2, (1,2):[1,2]}
(1)访问字典元素:
键放入中括号内访问字典元素: print(dict1['k1'])
(2)添加,修改字典元素:
1 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} 2 dict['Age'] = 8; # 更新 Age 3 dict['School'] = "CSU" # 添加信息
(3)删除字典元素:
1 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} 2 del dict['Name'] # 删除键 'Name' 3 dict.clear() # 清空字典 4 del dict # 删除字典
(4)字典内置函数len(), str(), type:
1 dict2 = {'Name': 'Joshua', 'Age': 7, 'Class': 'Math'} 2 print("length of dict2:", len(dict2)) #计算字典元素个数,即键的总数。 3 print(str(dict2)) #输出字典以可打印的字符串表示 4 print(type(dict2)) #返回输入的变量类型,如果变量是字典就返回字典类型。
1 length of dict2: 3 2 {'Age': 7, 'Name': 'Joshua', 'Class': 'Math'} 3 <class 'dict'>
(5)字典常用内置方法:
-get()
1 name = dict2.get('Name') #返回指定键的值,如果值不在字典中返回default值 2 print("name:", name)
-item(),keys(),values()
1 print(dict2.items()) 2 for item in dict2.items(): #以列表返回可遍历的(键, 值) 元组数组 3 print(item, type(item)) 4 for key in dict2.keys(): #以列表返回一个字典所有的键 5 print(key) 6 for value in dict2.values(): #以列表返回字典中的所有值 7 print(value)
1 dict_items([('Name', 'Joshua'), ('Class', 'Math'), ('Age', 7)]) 2 ('Name', 'Joshua') <class 'tuple'> 3 ('Class', 'Math') <class 'tuple'> 4 ('Age', 7) <class 'tuple'> 5 Name 6 Class 7 Age 8 Joshua
-clear(),copy()
1 #clear(),copy() 2 dict3 = dict2.copy() #返回一个字典的浅复制 3 print(id(dict2), dict2) 4 print(id(dict3), dict3) 5 dict3.clear() #清空字典内所有元素 6 print(dict3)
1 4301648 {'Age': 7, 'Class': 'Math', 'Name': 'Joshua'} 2 4301688 {'Age': 7, 'Class': 'Math', 'Name': 'Joshua'} 3 {}
最后看以下dict类的定义:
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 def clear(self): # real signature unknown; restored from __doc__ 14 """ D.clear() -> None. Remove all items from D. """ 15 pass 16 17 def copy(self): # real signature unknown; restored from __doc__ 18 """ D.copy() -> a shallow copy of D """ 19 pass 20 21 @staticmethod # known case 22 def fromkeys(*args, **kwargs): # real signature unknown 23 """ Returns a new dict with keys from iterable and values equal to value. """ 24 pass 25 26 def get(self, k, d=None): # real signature unknown; restored from __doc__ 27 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 28 pass 29 30 def items(self): # real signature unknown; restored from __doc__ 31 """ D.items() -> a set-like object providing a view on D's items """ 32 pass 33 34 def keys(self): # real signature unknown; restored from __doc__ 35 """ D.keys() -> a set-like object providing a view on D's keys """ 36 pass 37 38 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 39 """ 40 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 41 If key is not found, d is returned if given, otherwise KeyError is raised 42 """ 43 pass 44 45 def popitem(self): # real signature unknown; restored from __doc__ 46 """ 47 D.popitem() -> (k, v), remove and return some (key, value) pair as a 48 2-tuple; but raise KeyError if D is empty. 49 """ 50 pass 51 52 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 53 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 54 pass 55 56 def update(self, E=None, **F): # known special case of dict.update 57 """ 58 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 59 If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] 60 If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v 61 In either case, this is followed by: for k in F: D[k] = F[k] 62 """ 63 pass 64 65 def values(self): # real signature unknown; restored from __doc__ 66 """ D.values() -> an object providing a view on D's values """ 67 pass