如何将python中的字典变成列表

 时间:2024-09-20 17:52:17

python中,字典可用于存储对应关系的数据,比如一个学生的各科成绩。但如果需要存储多个学生的各科成绩,就需要将每个字典再组成列表。接下来介绍两种将字典转化成列表的方法。

工具/原料

python3

第一种方法:list.append()将字典作为元素添加到列表

1、首先,新建一个空列表。代码示例如下:info=[]

如何将python中的字典变成列表

2、然后,新建3个字典用于存储3个学生的各科成绩。代码示例如下:student_1={"Chinese":99,"Math":129,"English":145}student_2={"Chinese":98,"Math":139,"English":135}student_3={"Chinese":95,"Math":125,"English":130}

如何将python中的字典变成列表

3、接着用list.append()的方法将存储学生1成绩的字典添加到列表中。代码示例如下:info.append(student_1)info

如何将python中的字典变成列表

4、如需将所有存储学生成绩的字典放入列表中水貔藻疽,需要依次用list.append()的方法添加。完整的代码如下:info=[柯计瓤绘]student_1={"Chinese":99,"Math":129,"English":145}student_2={"Chinese":98,"Math":139,"English":135}student_3={"Chinese":95,"Math":125,"English":130}info.append(student_1)info.append(student_2)info.append(student_3)info

如何将python中的字典变成列表

第二种方法:直接将字典当成元素生成列表

1、第一种方法中,list.append()的方法只能一个个添加列表元素。对于已经存在的字典侍厚治越元素,我们也可以直接将其当成元素生成列表。代码姨胀兽辱示例如下:student_1={"Chinese":99,"Math":129,"English":145}student_2={"Chinese":98,"Math":139,"English":135}student_3={"Chinese":95,"Math":125,"English":130}info=[student_1,student_2,student_3]info

如何将python中的字典变成列表

2、但是现成的字典当成元素添加到列表之后,如果再需要添加新元素,仍然需要使用list.append()的方法增加新元素。代码示例如下:student_4={"Chinese":98,"Math":95,"English":136}info.append(student_4)info

如何将python中的字典变成列表

python删除重复元素 python大小写字母转换 python创建列表 python输出怎么换行 python中如何获取列表的最大值和最小值?
热门搜索
在线图片编辑 创意素描图片 滚图片 百花缭乱漫画 狗狗的品种及图片