1 dic = {"name" : "wangmo" ,"age" : 18} 2 3 #dic.clear() #清空字典 4 print(dic) 5 #{} 6 7 dic1=dic.copy() #复制字典 8 print(dic1) 9 #{‘name‘: ‘wangmo‘, ‘age‘: 18} 10 11 dic1=dict.fromkeys("hello",1) #快速生成字典 12 print(dic1) 13 #{‘o‘: 1, ‘h‘: 1, ‘l‘: 1, ‘e‘: 1} 14 15 print(dic.get("name")) #查看字典中是否存在此key,没有提示none 16 #wangmo 17 18 print(dic["name"]) #查看字典中是否存在此key,没有会报错 19 #wangmo 20 21 print(dic.items()) #将每对key-value表示成列表中元组的形式 22 #dict_items([(‘name‘, ‘wangmo‘), (‘age‘, 18)]) 23 24 for i in dic.items(): #循环输出每个项目 25 print(i) 26 # (‘name‘, ‘wangmo‘) 27 # (‘age‘, 18) 28 29 for k,v in dic.items(): #循环输出每个项目 30 print(k,v) 31 # name wangmo 32 # age 18 33 34 print(dic.keys()) #输出字典的key值 35 #dict_keys([‘name‘, ‘age‘]) 36 37 for i in dic.keys(): #循环输出字典的key值 38 print(i) 39 # name 40 # age 41 42 for i in dic.keys(): #可以循环输出key和value 43 print(‘key is %s,value is %s‘ %(i,dic[i])) 44 # key is age,value is 18 45 # key is name,value is wangmo
时间: 2024-10-20 18:07:52