python学习day4--python基础--字典

时间:2024-01-17 10:35:08

字典的常用操作:

 #字典天然去重,key唯一,如果key相同,只能打印出一个
id_db={
220456789852963741:{
'name':"alex",
'age':34,
'addr':'Dong'
},
220456789852963742:{
'name':"tom",
'age':34,
'addr':'Xi'
},
220456789852963743:{
'name':"mark",
'age':34,
'addr':'Nan'
}
}
print(id_db)
print(id_db[220456789852963741])#查看
id_db[220456789852963741]['name']="alexnew"#修改
print(id_db[220456789852963741])
id_db[220456789852963741]['qq']=""#添加
print(id_db[220456789852963741])
'''
id_db[220456789852963744]={
'name':"mark2",
'age':34,
'addr':'Nanjing'
} #添加
print(id_db)
''' #删除
del id_db[220456789852963741]['qq']
print(id_db[220456789852963741])
id_db[220456789852963741].pop('addr')
print(id_db[220456789852963741])
v=id_db.get(220456789852963741)
print(v)
dict2={
'name':'dddddddddd',
220456789852963743:{
'name':"mark",
'age':34,
'addr':'NanNing'
}
}
#如有相同id,则替换该id对应的所有值,如id不同,则添加到字典中
id_db.update(dict2)
print(id_db)
print(id_db.items())#将字典转换为列表
print(id_db.values())#打印所有的values
print(id_db.keys())#打印所有的keys
#查询是否含有某个key,id_db.has_key(220456789852963741)#only in 2.X
#in 3.X
print(220456789852963741 in id_db)
print('name' in id_db)
#setdefault,如果存在对应id则取值,不存在则返回null,并创建对应的key:value
print(id_db.setdefault(220456789852963741,{'name':"mark",
'age':34,
'addr':'NanNing'}))
print(id_db.setdefault(220456789852963745,{'name':"mark22",
'age':36,
'addr':'NanNing'}))
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])