[英]Append dictionary to a list in loop python
我正在嘗試執行類似於以下代碼的操作,但不是像代碼中的最后一行那樣打印,而是在尋找 output 以顯示為字典列表。
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).
謝謝
如果您只是想打印字典列表,為什么不直接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)
如果你想讓你的循環工作:
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)
這對我有用,以避免按字母順序對列表進行排序。 pprint 弄亂了排序,因此必須在下面使用才能使其正常工作。
pprint(students_list, sort_dicts=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.