字典的常用操作:
1 #字典天然去重,key唯一,如果key相同,只能打印出一个 2 id_db={ 3 220456789852963741:{ 4 'name':"alex", 5 'age':34, 6 'addr':'Dong' 7 }, 8 220456789852963742:{ 9 'name':"tom", 10 'age':34, 11 'addr':'Xi' 12 }, 13 220456789852963743:{ 14 'name':"mark", 15 'age':34, 16 'addr':'Nan' 17 } 18 } 19 print(id_db) 20 print(id_db[220456789852963741])#查看 21 id_db[220456789852963741]['name']="alexnew"#修改 22 print(id_db[220456789852963741]) 23 id_db[220456789852963741]['qq']="658742314"#添加 24 print(id_db[220456789852963741]) 25 ''' 26 id_db[220456789852963744]={ 27 'name':"mark2", 28 'age':34, 29 'addr':'Nanjing' 30 } #添加 31 print(id_db) 32 ''' 33 34 #删除 35 del id_db[220456789852963741]['qq'] 36 print(id_db[220456789852963741]) 37 id_db[220456789852963741].pop('addr') 38 print(id_db[220456789852963741]) 39 v=id_db.get(220456789852963741) 40 print(v) 41 dict2={ 42 'name':'dddddddddd', 43 220456789852963743:{ 44 'name':"mark", 45 'age':34, 46 'addr':'NanNing' 47 } 48 } 49 #如有相同id,则替换该id对应的所有值,如id不同,则添加到字典中 50 id_db.update(dict2) 51 print(id_db) 52 print(id_db.items())#将字典转换为列表 53 print(id_db.values())#打印所有的values 54 print(id_db.keys())#打印所有的keys 55 #查询是否含有某个key,id_db.has_key(220456789852963741)#only in 2.X 56 #in 3.X 57 print(220456789852963741 in id_db) 58 print('name' in id_db) 59 #setdefault,如果存在对应id则取值,不存在则返回null,并创建对应的key:value 60 print(id_db.setdefault(220456789852963741,{'name':"mark", 61 'age':34, 62 'addr':'NanNing'})) 63 print(id_db.setdefault(220456789852963745,{'name':"mark22", 64 'age':36, 65 'addr':'NanNing'})) 66 print(id_db)
# 循环字典
for k,v in id_db.items():#效率低,因为要有一个dist to list的转换过程
print(k,v)
#用如下方法效率高
for key in id_db:
print(key,id_db[key])