有时候,需要将一系列字典嵌套在列表中,或将列表作为值嵌套在字典中,这成为嵌套。可以在列表中嵌套字典,字典中嵌套列表甚至在字典中嵌套字典
列表中嵌套字典
例子1
student_1 = {'first': 'xin', 'last': 'zhu', 'age': 20}
student_2 = {'first': 'chun', 'last': 'lee', 'age': 21}
student_3 = {'first': 'meng', 'last': 'chen', 'age': 18}
students = [student_1, student_2, student_3] //创建一个列表,包括上面3个字典
for student in students: //根据for循环依次从列表中提取出每个字典
print(student)
//输出结果为:
{'first': 'xin', 'last': 'zhu', 'age': 20}
{'first': 'chun', 'last': 'lee', 'age': 21}
{'first': 'meng', 'last': 'chen', 'age': 18}
例子2
students = [] #创建一个空列表
for student_number in range(10): #这个表达式唯一的用途是告诉python要重复循环多少次,如这里10次,从0~9;每次执行这个循环事,都创建一个新的字典new_student,并把这个新的字典加入到列表students中末尾
new_student = {'major': 'biology', 'year': 2019, 'dormitory': 'jin ling'}
students.append(new_student)
for student in students[:3]: #使用切片来打印前3个学生的信息,如0~2
print("the new student live in " + student["dormitory"] + " study " + student["major"] + " in " +
str(student["year"]))
# 输出结果为:
the new student live in jin ling study biology in 2019
the new student live in jin ling study biology in 2019
the new student live in jin ling study biology in 2019
print("the total number of students is: " + str(len(students))) # 统计存在列表students中总的学生人数
#输出结果为:10
for student in students[:3]: #鉴于我们要修改前面3个学生的信息,我们需要遍历前3个学生的信息
if student['year'] == 2019: #如果学生入学的年份为2019,就修改为2020
student['year'] = 2020
for student in students[0:5]: #修改完前面3个学生的信息后,然后打印列表(students)中前5个学生的信息
print(student)
#输出结果为:
{'major': 'biology', 'year': 2020, 'dormitory': 'jin ling'}
{'major': 'biology', 'year': 2020, 'dormitory': 'jin ling'}
{'major': 'biology', 'year': 2020, 'dormitory': 'jin ling'}
{'major': 'biology', 'year': 2019, 'dormitory': 'jin ling'}
{'major': 'biology', 'year': 2019, 'dormitory': 'jin ling'}
在字典中存储列表
class_2006 = {"major": "biology", "year": 2006, "students": ["lee", "chen", "yi", "meng"]} #创建了一个字典,包括了一个班的信息,如专业,年份和学生,由于一个班的学生是有多个,因此与之相关联的值为一个列表
print("The major " + class_2006["major"] + " in " + str(class_2006['year']) + " have the following students: ")
for student in class_2006['students']: #利用for循环访问列表中的每个学生
print(student.title())
#输出结果为:
The major biology in 2006 have the following students:
Lee
Chen
Yi
Meng
在字典中存储字典
students = {"lee": {"major": "biology", "year": 2007, "province": "guangdong"},
"chen": {"major": "ecology", "year": 2008, "province": "sichuang"}} #定义了一个字典,其中包含了两个键,每个键相关联的值为一个字典,其中包含每个学生的专业,入学年份和籍贯
for names, info in students.items(): #遍历字典studnets,让Python依次将每个键存储在变量names中,然后将与之相关联的值存储在变量info中,然后在循环内部(如下面的代码块)将每个学生的信息都打印出来
print(names.title() + " study " + info['major'] + " in " + str(info["year"]) + " come from " + info["province"])
#输出结果为:
Lee study biology in 2007 come from guangdong
Chen study ecology in 2008 come from sichuang