1) Dictionary-related operation methods
Infos ={' name ': ' Zhang San ', ' sex ': ' Male ', ' addr ': ' Guangzhou ', ' age ': ' 20 '}
#查找
Infos.get (' name ') #获取name对应的值
Infos. [' Sex '] #获取sex对应的值,
Infos.get (' phone ') #取不到这个key的话, is None
Infos.get (' phone ') #如果取不到这个值, the default is 110
infos[' Blood_type '] #如果key不存在, you will get an error
#增加
infos[' phone '] = 12345656787 #增加一个key
Infos.setdefault (' Deposit ', ' 20000 ') #增加一个key-value
Infos.setdefault (' name ', ' Wowo ') #如果Key存在的话, does not modify the original key value
#修改
infos[' name ']= ' Tata '
Infos.update ({' Native_place ': ' Hunan ', ' phone ': ' 14567877878 ') is added #如果key不存在, if key is present, modify
#删除
Infos.pop (' name ') #删除指定的key
Infos.popitem () #随机删除一个key
Del infos[' phone '] #删除指定的key
Infos.clear () #清空字典
#方法
Infos.values () #获取到字典所有的value
Infos.keys () #获取到字典所有的key
Infos.items () #获取到字典所有的key-value
Write a little exercise:
# Write a program to enter students ' homework status
# 1, check the student work situation
# 2. Entry of student's homework
# 3, can let input 3 times, need to verify the case of empty
Homeworks = {#先定义一个字典
' Zhang San ': {' 2018.3.23 ': ' Not delivered ', ' 2018.3.24 ': ' Delivered '},
' John Doe ': {' 2018.3.23 ': ' Delivered ', ' 2018.3.24 ': ' Delivered '},
' Liu Wu ': {' 2018.3.23 ': ' Not delivered ', ' 2018.3.24 ': ' Not Delivered '},
}
For I in range (3): #进入三次循环
Operation = input ("'
1. View Student Assignments
2. Entry of student assignments
Please select the action you want to do: "). Strip ()
if operation = = ' 1 ': #选择查看学生信息, print out all student information
For k,v in Homeworks.items ():
Print (k, ' ==> ', v)
Elif operation== ' 2 ': #选择录入学生信息
Name = input (' Please enter student's name: '). Strip ()
Time = input (' Please enter date (xxxx.xx.xx): '). Strip ()
Status = Input (' Enter job status (not Delivered/delivered): '). Strip ()
If name in Homeworks: #如果学生名字存在字典中
Homeworks[name].update ({time:status})
else: #如果学生名字不存在字典中
Homeworks.update ({name:{time:status}})
Print (' Operation succeeded ')
Else
Print (' Please enter the correct selection! ‘)
Else
Print (' Allow operation only three times. ‘)
Beginners Learn Python (iii) How to work with dictionaries