【问题标题】:Filling a dictionary with multiple user input用多个用户输入填充字典
【发布时间】: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


    【解决方案1】:

    几个项目:

    您可以通过创建一个包含已填充键的字典来节省一些代码,然后只需遍历键以提示用户。

    您转储 json 的方式不正确。我很惊讶它正在读回它。您文件的顶级 json 结构应该是一个列表。列表内部是用户配置文件字典的集合。添加新字典时,您需要读入文件内容,追加新字典,然后再次写出整个文件。

    从长远来看,它有助于将单独的任务分解为单独的功能。它使代码更易于管理。

    import os
    import json
    
    def collect_data():
        """Collect user input to build a dating profile and store it in a
        dictionary """
        date_profile = {
            'first_name' : '',
            'surname': '',
            'gender': '',
            'age': '',
            'location': ''
        }
    
        validations = {
            'first_name' : (None, None),
            'surname': (None, None),
            'gender': (validate_gender, 'Please select either "male" or "female".'),
            'age': (int, 'Age must be an integer.'),
            'location': (None, None)
        }
    
        for key in date_profile:
            value = query_user(key)
            if value is None:
                return
            validate, msg = validations.get(key)
            if validate:
                retry = True
                while retry: 
                    try:
                        validate(value)
                        retry = False
                    except:
                        print(msg)
                        value = query_user(key)
                        if value is None:
                            return
            date_profile[key] = value
        return date_profile
    
    def export_profile(file_path, date_profile):
        # read in json, or create new list
        if os.path.exists(file_path):
            with open(file_path) as fp:
                j_data = json.load(fp)
        else:
            j_data = []
        j_data.append(data_profile)
        # write out
        with open(file_path, 'w') as fp:
            json.dump(j_data, fp)
    
    def query_user(key):
        query = "Enter your {} (type 'quit' to exit): ".format(key.replace('_', ' '))
        value = input(query)
        if value.lower() == 'quit':
            print('Exiting.')
            return None
        return value
    
    def validate_gender(g):
        assert g.lower() in ('male', 'female')
    
    if __name__ == '__main__':
        dp = collect_data()
        export_profile("dating_profile.json", dp)
    
    

    要运行它,请将其保存到 python 文件中,例如 collect.py 并运行:

    python collect.py
    

    【讨论】:

    • 我也想问。在第一个例外语句中,您写了例外是什么?
    • 没问题。如果它回答了您的问题,请单击答案旁边的复选标记。 except 块将捕获任何因尝试验证数据条目而引发的异常。你可以把它写成两个除了块,一个用于ValueError,另一个用于AssertionError,但是块中的代码是一样的。
    【解决方案2】:

    如果您的文件中有超过 1 个 json 对象,则它不再有效,这就是您收到错误的原因。您应该将您的 date_profile 附加到一个列表并每次重写整个文件,或者每个配置文件只有一个文件。

    【讨论】:

      【解决方案3】:

      您的 JSON 文件无效。您可以使用validator 来验证它。 一个快速的解决方法是将它存储在一个数组中并转储一次。

      [
      {profile_1},
      {profile_2},
      {profile_3}
      ]
      

      持久化数据的替代方法是Pickle

      尽管我建议您使用数据库来存储数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 2022-06-15
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多