【发布时间】:2019-12-26 13:44:54
【问题描述】:
我正在尝试创建一个存储用户数据的字典,以便为该用户创建个人资料。但是每当我运行我的程序并输入转义词以退出运行程序时,程序只打印用户输入的最后几条信息(最后一个配置文件说)。但我希望能够像字典一样保存和打印每个配置文件,所以它应该列出一个嵌套字典并保存在一个 json 文件中,但我被卡住了。
这是我的代码:
def collect_data():
"""Collect user input to build a dating profile and store it in a
dictionary """
date_profile = {}
dating_file = "dating_profile.json"
while True:
# Prompt the user for his/her name, age, gender, date of birth and
# location
name = "name"
first_name = input("Enter your first name: ")
if first_name == 'quit':
break
surname = "surname"
last_name = input("Enter your last name: ")
if last_name == 'quit':
break
sex = "sex"
gender = input("What is your gender? Male or Female: ")
if gender == 'quit':
break
lifespan = "age"
age = input("Enter your age: ")
try:
age = int(age)
except ValueError:
print(input("Invalid value! Please enter your age"))
locality = "location"
location = input("Please enter your location: ")
if location == 'pass':
pass
elif location == 'quit':
break
# Store the user's data in a dictionary
date_profile[name] = first_name
date_profile[surname] = last_name
date_profile[sex] = gender
date_profile[lifespan] = age
date_profile[locality] = location
with open(dating_file, 'a') as f:
json.dump(str([date_profile]), f)
def retrieve_data():
"""Re-downloads the data stored in dating_file.json"""
with open("dating_profile.json") as f_object:
download_profile = json.load(f_object)
print(download_profile)
collect_data()
retrieve_data()
这是我在终端中收到的错误消息: enter image description here
【问题讨论】:
标签: python json python-3.x dictionary