在循环Python中将字典追加到列表中

时间:2020-05-09 08:00:02

标签: python

我正在尝试执行与以下代码类似的操作,但不是像代码中的最后一行那样打印, 我正在寻找要显示为字典列表的输出。

import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
    for jsonObj in f:
    studentDict = json.loads(jsonObj)
    studentsList.append(studentDict)
print("Printing each JSON Decoded Object")
for student in studentsList:
    print(studentList) # Output is not looping , I get the following [{'id': 
    1, 'first_name': 'name1'}] but repeated 10 times in row instead it needs 
    to increment id until 10 with 1-10 id). 

谢谢

2 个答案:

答案 0 :(得分:2)

如果您只想打印字典列表,为什么不只做print(studentsList)

它看起来像这样:

import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
    for jsonObj in f:
      studentDict = json.loads(jsonObj)
      studentsList.append(studentDict)
print("Printing the list of JSON Decoded Objects")
print(studentList)

输出: Without Loop

如果您希望循环起作用:

import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
    for jsonObj in f:
      studentDict = json.loads(jsonObj)
      studentsList.append(studentDict)
print("Printing the list of JSON Decoded Objects")
for student in studentsList:
    print(student)

输出: With Loop

答案 1 :(得分:0)

这对我很有帮助,避免了按字母顺序对列表进行排序。 pprint弄乱了排序,因此必须在下面使用才能使其正常工作。

pprint(students_list,sort_dicts = False)