字典常用方法
1 字典的表示方法: 2 3 info_dic={'name':'haiyna','age':18,'sex':'female'} 4 # 常用操作: 5 # 6 1.存/取 7 info_dic={'name':'egon','age':18,'sex':'male'} 8 print(info_dic['name11111111'])#找不到则报错了 9 print(info_dic.get('name',None)) 10 print(info_dic.get('name222222',None))#get方法找不到不报错,可以自己设定默认值 11 12 #pop:key存在则弹出值,不存在则返回默认值,如果没有默认值则报错 13 # print(info_dic.pop('nam123123123123123123e',None)) 14 # print(info_dic) 15 16 # print(info_dic.popitem()) 17 # print(info_dic) 18 19 # info_dic['level']=10 20 # print(info_dic) 21 22 # 23 # 删除 24 info_dic={'name':'egon','age':18,'sex':'male'} 25 # info_dic.pop() 26 # info_dic.popitem() 27 28 # del info_dic['name'] 29 30 31 # 32 # 键s,值s,键值对 33 info_dic={'name':'egon','age':18,'sex':'male'} 34 # print(info_dic.keys()) 35 # print(info_dic.values()) 36 # print(info_dic.items()) 37 38 # for k in info_dic: 39 # # print(k,info_dic[k]) 40 # print(k) 41 42 # print('========>') 43 # for k in info_dic.keys(): 44 # print(k) 45 46 # for val in info_dic.values(): 47 # print(val) 48 49 # for k,v in info_dic.items(): #k,v=('name', 'egon') 50 # print(k,v) 51 52 53 54 # 长度 55 # info_dic={'name':'egon','age':18,'sex':'male'} 56 # print(len(info_dic)) 57 # 58 # 循环 59 # 60 # 包含in 61 62 # info_dic={'name':'egon','age':18,'sex':'male'} 63 # print('name' in info_dic) 64 # print('name' in info_dic.keys()) 65 # print('egon' in info_dic.values()) 66 # print(('name','egon') in info_dic.items()) 67 68 69 70 #掌握 71 info_dic={'name':'egon','age':18,'sex':'male'} 72 # info_dic.update({'a':1,'name':'Egon'}) 73 # print(info_dic) 74 75 # info_dic['hobbies']=[] 76 # info_dic['hobbies'].append('study') 77 # info_dic['hobbies'].append('read') 78 # print(info_dic) 79 80 #setdefault:key不存在则设置默认值,并且放回值默认值 81 #key存在则不设置默认,并且返回已经有的值 82 83 # info_dic.setdefault('hobbies',[1,2]) 84 # print(info_dic) 85 # info_dic.setdefault('hobbies',[1,2,3,4,5]) 86 # print(info_dic) 87 88 # info_dic={'name':'haiyan','age':18,'sex':'male'} 89 90 # {'name':'egon','age':18,'sex':'male','hobbies':['study']} 91 # info_dic.setdefault('hobbies',[]).append('study') 92 93 # {'name':'egon','age':18,'sex':'male','hobbies':['study','read']} 94 # info_dic.setdefault('hobbies',[]).append('read') 95 96 # {'name':'egon','age':18,'sex':'male','hobbies':['study','read','sleep']} 97 # info_dic.setdefault('hobbies',[]).append('sleep') 98 # l=info_dic.setdefault('hobbies',[]) 99 # print(l,id(l)) 100 # print(id(info_dic['hobbies'])) 101 102 # print(info_dic) 103 104 105 106 #了解 107 # d=info_dic.copy() 108 # print(d) 109 # info_dic.clear() 110 # print(info_dic) 111 112 113 # d=info_dic.fromkeys(('name','age','sex'),None) 114 # print(d) 115 # d1=dict.fromkeys(('name','age','sex'),None) 116 # d2=dict.fromkeys(('name','age','sex'),('egon',18,'male')) 117 # print(d1) 118 # print(d2) 119 120 121 122 123 # info=dict(name='haiyan',age=18,sex='male') 124 # print(info) 125 126 # 127 # info=dict([('name','haiyan'),('age',18)]) 128 # print(info)
归类 : python相关