#字典类型 key -- value 键值是唯一的,值则不必
#访问字典里的值
dict={
'alice':'123','beth':'13','cecil':'3258'}
print(type(dict))
print(dict['alice'])
print(dict['beth'])
print(dict['cecil'])
#修改字典
dict['alice']=1
dict['class']='2'
print(dict)
#删除字典元素
del dict['alice']#删除键是alice的条目
print(dict)
dict.clear()#清空词典所有条目
print(dict)
'''
'''
dict={
'alice':'123','beth':'13','cecil':'3258'}
del dict#删除词典
print(dict)
'''
'''
#1.不许同一个键出现2次,同一个键被赋值2次,后一个值会被记住
#2.键值须不可变,可以用数字,字符串,元组充当,列表就不行
dict={
1:'123','beth':'13',(1,2):'1235'}
#dict={1:'123','beth':'13',(1,2):'1235',['11']:'12'} error
print(dict)
#字典长度
print(len(dict))
#清除字典里数据
dict.clear()
print(dict)
del dict
print(dict) #删除字典
'''
'''
#获取字典所有键值函数
dict={
1:'123','beth':'13',(1,2):'1235'}
print("keys: ",dict.keys())
#返回指定键的值
print(dict.get(1))
print(dict.get('1'))#若值不在字典中返回默认值None
print(dict.get((1,2)))#None
'''
'''
#字典存储学生信息
def getstudent():
global st#全局变量定义
st=[]#列表初始化
st.append({
"name":"xiaoming","gender":"man","age":"12"})#字典插入列表
st.append({
"name":"lihua","gender":"man","age":"13"})
st.append({
"name":"xiaofan","gender":"woman","age":"22"})
def seekstudent(name):
for s in st:#列表使用
if s["name"]==name:
print(s)
print(s["name"],s["gender"],s["age"])
return
print("no this name")
getstudent()
seekstudent("lihua")
seekstudent("sss")
'''
'''
#字典作为函数参数
# 如果在函数中改变了字典,那么调用处的字典也同时被改变,也就是说调用处的实际参数与函数形式参数是同一个变量
def fun(dict):
dict["name"]="xxx"
dict={
"name":"xiaoyun","age":"18","six":"man"}
print(dict)
fun(dict)
print(dict)
'''
'''
#函数返回字典
def fun():
dict={
}
dict["name"]="aaa"
dict["age"]=12
dict["gender"]="male"
return dict
def show(dict):
keys=dict.keys()
for key in keys:
print(key,dict[key])
dict=fun()
print(dict)
show(dict)
'''
'''
#字典与字典参数 **表示字典可变参数
# 如果函数有*args及**kargs参数同时存在时,那么*args必须放在**kargs前面,函数最后2个参数为*args,**kargs
def fun(x,y=2,**kargs):
print(x,y)
print(kargs)
fun(1,2)
fun(1,2,z=3)
fun(1,2,a=3,b="demo")
fun(x=1,y=2,z=3)
fun(y=1,x=2,z=5,s="demo")
fun(x=1,z=3)
'''
'''
#具有元组可变参数与字典可变参数的函数
def fun(x,y=2,*args,**kargs):
print(x,y)
print(args)
print(kargs)
fun(1,2)
fun(1,2,3,4)
fun(1,2,3,4,z=5,s="demo")
#fun(x=1,y=2,3,4) #error
#由于*args 的参数时位置参数,因此有*args 出现时,*args 前面的函数参数在调用时不能
#以关键字参数的方式出现,只能以位置参数的方式出现,例如下列是错误的调用:
#fun(x=1,y=2,3,4)
python基础复习(34)--字典{}
猜你喜欢
转载自blog.csdn.net/xt18971492243/article/details/112266960
今日推荐
周排行