python - 用多个用户输入填充字典
问题描述
我正在尝试创建一个存储用户数据的字典,以便为该用户创建配置文件。但是每当我运行我的程序并输入转义词以退出运行程序时,程序只打印用户输入的最后几条信息(最后一个配置文件说)。但我希望能够像字典一样保存和打印每个配置文件,所以它应该列出一个嵌套字典并保存在一个 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()
这是我在终端中收到的错误消息: 在此处输入图像描述
解决方案
如果您的文件中有超过 1 个 json 对象,则它不再有效,这就是您收到错误的原因。您应该将您附加date_profile
到列表并每次重写整个文件,或者每个配置文件有一个文件。
推荐阅读
- javascript - {"error":"unsupported_grant_type"} while get token from my rest api on flutter
- python - Model prediction in data generator Keras
- java - SAX parser won't ignore non included element attribute in bean definition while unmarshalling
- facebook - AppSync/Graphql 多个订阅或多个 id 的一个订阅?
- java - Dealing With Simultaneous Collisions in Java
- sapui5 - How do I Split up batch OData requests
- c++ - 即使在同一类型上,也应该使用放置 new 调用析构函数
- javascript - 当使用 Jquery/JavaScript 单击上一个列表项时,如何定位嵌套在列表项中的元素?
- jhipster-registry - Jhipster 注册表给了我一个退出:io.github.jhipster.registry.service.ZuulUpdaterService.updateZuulRoutes() with result = null
- javascript - getter function name 'doEmptyItemsExist'