Python Forum

Full Version: How to reuse data from variables?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My question is rather simple and straight forward.
I've got this piece of code:

import shelve

Info=shelve.open("Info")

data={}

def add():
    while True:
        print ("User ID: ")
        usr=input(">>> ")
        print ("User Name: ")
        name=input(">>> ")
        print ("User Ager: ")
        age=input(">>> ")
        print ("User Gender: ")
        gender=input(">>> ")
        datos[usr]=[name, age, gender]
        print ("Add another entry?")
        op=input(">>> ")
        if str(op)=="s":
            del(name)
            del(age)
            del(gender)
            continue
        else:
            break
add()
Info["Data"]=data

Info.close()
And this other one:

import shelve
Info=shelve.open("Info")
pref=["Name: ", "Age: ", "Gender: "]
for i, j in Info["Data"].items():
    print (i)
    for k, l in enumerate(j):
        print ("\t"+str(pref[k]).ljust(10)+str(l).rjust(15))
    print ()
Info.close()
I know the error is in initializing the dict "data" as and empty dict every time I run the script, but I can't figure out how to store data and add any new data to the already stored.
There is a nice introduction to shelve with a good example in PyMOTW3 shelve
I don't know if it's ok to post the solution I came up with, but finally I was able to solve it.
So basically, I was using a new dict instead of the shelve object that behaves like a dictionary.