python学习3-使用dict

#构造 d = dict(one = 33, two = 44) print(d) d0 = dict({'one' : 55, 'two' : 66}) print(d0) d1 = dict(zip(('one', 'two'), (77, 88))) print(d1) d2 = dict([('one', 3), ('two', 4)]) print(d2) d3 = {} print(d3) d4 = dict() print(d4) #计算元素个数 print(len(d)) #__missing__,key不存在将调用它 class subDict(dict): def __missing__(self, key): return key + 'is not exist' subd = subDict() print(subd['123']) d['three'] = 99 print(d) #删除一个元素 del d['three'] print(d) #in, not in使用 print('one' in d) print('three' in d) print('three' not in d) print('one' not in d) #取得迭代器集合 for it in iter(d): print(it) #拷贝整个字典集合 d5 = d.copy() print(d) print(d5) d['three'] = 99 print(d) print(d5) #删除全部元素 d.clear() print(d) #类成员函数fromkeys的使用 d6 = dict.fromkeys(['1', '2'], 'liyong') print(d6) print(d6.get('1', 'default')) print(d6.get('3', 'default')) #dict view object list0 = d6.items() print(list0) for ite in list0: print(ite) list1 = d6.keys() print(list1) for ite in list1: print(ite) list3 = d6.values() print(list3) d6['5'] = 123456789 print(list3) #pop使用 print(d6.pop('3', 'defalut')) print(d6) print(d6.pop('1', 'defalut')) print(d6) #popitem使用 d6['3'] = 'cc' print(d6) list2 = d6.popitem() print(list2) for ite in list2: print(ite) #setdefault使用 If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None. print(d6.setdefault('5')) print(d6)

你可能感兴趣的:(python学习3-使用dict)