1. 创建字典
描述:生成字典
语法:
dic={'k1':'v1'}
样例:
dic=dict(k1='v1',k2='v2') dic={'k1':'v1','k2':'v2'}
2. 取键值get
描述:取键值,若字典中没有键,则输出自定义字段,默认为none
语法:
def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass
样例:
dic={'k1':'v1','k2':'v2'} a=dic.get('k1') v1 c=dic.get('k3') none #字典中无该键,显示none c=dic.get('k3','no') no #字典中无该键,显示no
3. 取键的值
描述:取字典中的键
语法:
def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass
样例:
dic=dict(k1='v1',k2='v2') dic.keys() for k in dic.keys(): print(k) result:k1, k2 #显示结果
4. 取键值
描述:取字典中的键值
语法:
def values(self): # real signature unknown; restored from __doc__ """ D.values() -> an object providing a view on D's values """ pass
样例:
dic=dict(k1='v1',k2='v2') for v in dic.values(): print(v) v=v1,v2 #结果
5. 取键值对的值
描述:取字典中的键值对
语法:
def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass
样例:
dic={'k1':'v1','k2':'v2'} for k,v in dic.items(): print(k,v) #结果 k1 v1 k2 v2
6. 删除键值对
描述:删除字典中的键
语法:
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
样例:
dic=dict(k1='v1',k2='v2',k3='v3') dic.pop('k2') print(dic) dic={'k3': 'v3', 'k1': 'v1'} #结果
7. 更新键值对
描述:更新字典中的键
语法:
def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then 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
样例:
dic=dict(k1='v1',k2='v2',k3='v3') dic.update({'k4':'v4'}) print(dic) dic={'k4': 'v4', 'k3': 'v3', 'k1': 'v1', 'k2': 'v2'} #结果
8. 更新键值
描述:更新字典中的键
语法:
dict[key]=value
样例:
dic=dict(k1='v1',k2='v2',k3='v3') dic['k1']=1 print(dic) dic={'k3': 'v3', 'k1': 1, 'k2': 'v2'} #结果