Home > Blockchain >  How to add a number to dict value every time i call it?
How to add a number to dict value every time i call it?

Time:03-25

I want to put a dictionary which contains user information into a new json file and i want it to give every user a number when i call a function 'new_user'. How can i do it?

from get_stars import rate_service
user_info = {
    'user_number': int(),
    'user_info': {
        'username': 'username',
        'user_location': 'user_location',
        'used_application': 'used_application',
        'stars': int()
    }
}

def get_user_info():
    new_user = user_info.copy()
    new_user['user_info']['username'] = input(f"\nEnter your name: ")
    new_user['user_info']['stars'] = rate_service()
    return new_user
from userinfo import get_user_info
import json

def new_user():
    user = get_user_info()
    filename = f"user.json"
    with open(filename, 'w'):
        json.dump(filename, user)

For example i call that func and in my json file there is dict with user number 1, but when i call it next time this number increases by 1

CodePudding user response:

If you want to avoid reading the file before assigning the number I would use a Guuid, that is basically a random number so big that is at all effects guaranteed not to collide with others.

If you want to assign a integer then you have two choices:

  1. reading the files taking the max value and assign before setting the user info
  2. having another file with the "metadata" of the user count which you will also read.

Normally this kind of operations are made using a database that will take care out of them.

You can also use a indexed dataframe a numerated dictionary or even a list of user as a middle data-structure that will help you if you go for the option 1.

CodePudding user response:

Assign a uuid: https://docs.python.org/3/library/uuid.html

import uuid

new_user = {}

new_user['user_number'] = uuid.uuid1()

# output: {'user_number': UUID('d2586590-abb8-11ec-94de-acde48001122')}
print(new_user)
  • Related