How to Persist User Data in Python Without Overwriting Existing Dictionaries

This article walks through a Python solution that loads user data from a JSON file, adds new usernames, emails, and passwords while preventing duplicates, and saves the updated information back, demonstrating practical data persistence without recreating dictionaries each run.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Persist User Data in Python Without Overwriting Existing Dictionaries

Introduction: The author, a Python enthusiast, received a question about how to add data to existing keys in a dictionary without recreating it each run.

Implementation Process

The solution modifies existing code to load data from a JSON file, append new usernames, emails, and passwords while avoiding duplicates, and then write the updated data back to the file.

import json

def load_data():
    try:
        with open('user.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return {
            "用户名": [],
            "密码": [],
            "邮箱": []
        }

def login(data):
    print("欢迎来到图书管理系统注册页面~")
    while True:
        username = input("请输入用户名:\t")
        if len(username) < 5:
            print("用户名不能小于5位")
        else:
            if username not in data["用户名"]:
                data["用户名"].append(username)
                email = input("请输入邮箱:\t")
                if email.endswith('@zxs.com'):
                    if email not in data["邮箱"]:
                        data["邮箱"].append(email)
                        password = input("请输入密码:\t")
                        if len(password) >= 6:
                            data["密码"].append(password)
                            print(f"Tips: 恭喜{username}注册成功,请前往登录")
                            save(data)
                            break
                        else:
                            print("密码不能小于6位")
                    else:
                        print("邮箱已存在,请使用其他邮箱注册")
                else:
                    print("邮箱格式错误,邮箱后缀必须是@zxs.com")
            else:
                print("用户名已存在,请使用其他用户名注册")

def save(data):
    try:
        with open('user.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
    except Exception as e:
        print("文件写入失败,请检查文件路径")

if __name__ == '__main__':
    data = load_data()
    login(data)

Conclusion: The script successfully resolves the original problem, showing how to persist user information in a JSON file while preventing duplicate entries.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JSONData Persistencedictionaryfile-iouser registration
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.