在列表中存储字典
我们先创建三个字典,每个字典代表着一个学生的信息,然后使用列表把这些学生信息装起来
student1 = {
'id' : 1,
'name' : '小明',
'age' : 18,
'class' : 'class one'
}
student2 = {
'id' : 2,
'name' : '小huang',
'age' : 18,
'class' : 'class two'
}
student3 = {
'id' : 3,
'name' : '小红',
'age' : 18,
'class' : 'class three'
}
student_list = [student1,student2,student3]
for student in student_list:
print(student)
生成10个学生信息
student_list = []
for student in range(1,10):
new_student = {'id':1,'name':'lisa','age':18}
student_list.append(new_student) #加入学生信息
new_student['id'] = student #id自增
print(student_list)
在字典中存储列表
我们先创建一个字典,里面存储学生信息,班级,课程
students = {
"student":["id","name","age"],
"class":["class_one","class_two"],
"course":["chinese","math","english"]
}
print(students['student'])
遍历字典
students = {
"student":["id","name","age"],
"class":["class_one","class_two"],
"course":["chinese","math","english"]
}
for item in students.items():
print(item)
在字典中还可以存储字典
字典除了可以存储列表之外,还可以存储字典,如:
students = {
"student1":{
"id":1,
"name":"Lisa",
"age":18
},
"student2":{
"id":2,
"name":"Jhon",
"age":19
},
"student3":{
"id":3,
"name":"WuLin",
"age":20
}
}
print(students['student1'])