1 创建字典
字典是一系列的键值对,每个键都与一个值对应,值可以是数、字符串、列表、字典等
#创建字典,如需要创建一个空的字典students_info={}
students_info={'jack':5,'andy':7,'kiki':6,'alicy':8}
#访问学生年龄
print(students_info.keys())
print(students_info.values())
print(f"Andy is {students_info['andy']} years old.")
运行结果:
dict_keys(['jack', 'andy', 'kiki', 'alicy']) dict_values([5, 7, 6, 8]) Andy is 7 years old. ?
2 字典操作
#字典操作
students_info={'jack':5,'andy':7,'kiki':6,'alicy':8}
students_info['allen']=7#添加键值对
print(students_info)
students_info['allen']=18#修改allen关联值改为18
print(students_info)
del students_info['allen']#删除allen键值对
print(students_info)
运行结果: {'jack': 5, 'andy': 7, 'kiki': 6, 'alicy': 8, 'allen': 7} {'jack': 5, 'andy': 7, 'kiki': 6, 'alicy': 8, 'allen': 18} {'jack': 5, 'andy': 7, 'kiki': 6, 'alicy': 8}
3 字典访问
(1)get访问
#字典访问
students_info={'jack':5,'andy':7,'kiki':6,'alicy':8}
#访问字典,若没有此键值,返回No this student,若没有指定第二个参数,返回None
student_age=students_info.get('andy', 'No this student.')
print(f"Andy is {student_age} years old.")
运行结果: Andy is 7 years old.
(2)遍历访问
#创建字典
students_info={'jack':5,'andy':7,'kiki':6,'alicy':8}
#访问字典,若没有此键值,返回No this student,若没有指定第二个参数,返回None
student_age=students_info.get('andy', 'No this student.')
print(f"Andy is {student_age} years old.")
#遍历键值对
students_info={'jack':5,'andy':7,'kiki':7,'alicy':8}
#遍历所有键和值
for key,value in students_info.items():
print(f"{key} is {value} years old.")
#遍历所有键,临时排序后遍历
for name in sorted(students_info.keys()):
print(f"student name is {name}")
#遍历所有值
for age in students_info.values():
print(age)
#查询年龄
students_name=['jack','kiki']
for name in students_name:
age=students_info[name]
print(f"{name} is {age} years old.")
#列出不重复的年龄大小,set
for age in set(students_info.values()):
print(f"不重复的年龄是:{age}")
#判断allen是否有年龄信息记录在案
if 'allen' not in students_info.keys():
print("Allen`s age is not in the table. \nPlease give information.")
运行结果:
Andy is 7 years old. jack is 5 years old. andy is 7 years old. kiki is 7 years old. alicy is 8 years old. student name is alicy student name is andy student name is jack student name is kiki 5 7 7 8 jack is 5 years old. kiki is 7 years old. 不重复的年龄是:8 不重复的年龄是:5 不重复的年龄是:7 Allen`s age is not in the table. Please give information.
|