Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

python - How to write a json file inside of a for loop?

How I can store the result of a for loop? How to creat a json file inside of a loop? In this loop in each iterate I am printing 2 values print(a1,a2). now I want to store all these value in a json file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shouldn't write json the file inside of the loop, you should build a dictionary or list of dictionaries, then write that with json.dump()

import json

# initialize the dictionary
my_dict = {}

# loop to emulate your data structure
for i in range(10):
    # assign a1 and a2
    a1 = i
    a2 = i ** 2 # just so the value is different than the key for demonstration
    # set a1 as the key and a2 as the value
    my_dict[a1] = a2

# use json.dump to write the file
with open('./square.json', 'w') as file:
    json.dump(my_dict, file, indent=4)

Output (square.json):

{
    "0": 0,
    "1": 1,
    "2": 4,
    "3": 9,
    "4": 16,
    "5": 25,
    "6": 36,
    "7": 49,
    "8": 64,
    "9": 81
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...