简体   繁体   English

Append 字典到循环中的列表 python

[英]Append dictionary to a list in loop python

I am trying to do something similar to the below code but instead of printing like last line in the code, I am looking for output to display as list of dicts.我正在尝试执行类似于以下代码的操作,但不是像代码中的最后一行那样打印,而是在寻找 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). 

Thanks谢谢

If you simply want to print the list of dicts, why don't you just do print(studentsList)如果您只是想打印字典列表,为什么不直接print(studentsList)

It would look like this:它看起来像这样:

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)

OUTPUT: OUTPUT: 无循环

If you want your loop to work:如果你想让你的循环工作:

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)

OUTPUT: OUTPUT: 带循环

This worked for me to avoid sorting alphabetically the list.这对我有用,以避免按字母顺序对列表进行排序。 pprint messes the sort so had to use below to make it work. pprint 弄乱了排序,因此必须在下面使用才能使其正常工作。

pprint(students_list, sort_dicts=False ) pprint(students_list, sort_dicts=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM