Hi attempting to make an address book program but hit a snag-
I have:
A class to give various attributes(phone numbers etc)to an instance
which then puts it all into a doc string which can be added to a dictionary-
but I want a function that will ask the user for the relevant information and then feed it to the class as the relevant arguments. however I Can't figure that out. Any Ideas-Section of code below:

class Data:
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
    def Coll_Data(self):
        self.info = """
Home Phone: %s
Mobile Phone: %s
Email: %s
""" % (self.home, self.mobile, self.email)

#the bit that doesn't work that needs changing is below:

def add_new():
    name = raw_input("Enter name to be added: ")
    h = raw_input("Enter home phone: ")
    m = raw_input("Enter Mobile phone: ")
    e = raw_input("Enter Email address: ")
    name = Data(h, m, e)

Please help!!!!!!

Oh I see, you want the instance name be the name of the person. That will not be a good idea, because identifiers in Python don't allow spaces.

A dictionary, where the name is the key and the value is a ( home, mobile, email ) tuple or list will do much better. You could also make the class instance the value of your dictionary.

Thanks, but making the class instance the value of the dictionary does not work it just returns the location of the instance in hexadecimal notation.

I have rejigged the code:

class Data:
    def __init__(self):
        self.home = raw_input("Enter home: ")
        self.mobile = raw_input("Enter mobile: ")
        self.email = raw_input("Enter email :")
    def Coll_data(self):
        self.info = """
Home : %s
Mobile : %s
Email : %s
""" % (self.home, self.mobile, self.email)

I intend to add it to the dictionary using self.info as the value.
But I really need a function that will create a variable and asign it to class Data.

This works just fine:

# create a dictionary of class instance values

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data
name = 'frank'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'

name_dic[name] = Data(home, mobile, email)

# second set of data
name = 'bob'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'

name_dic[name] = Data(home, mobile, email)

# get bob's email
name = 'bob'
print( name_dic[name].email )

print('-'*30)

# get the info for all names added so far
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

"""
my output -->
bob.dork@hotmail.com
------------------------------
Name = frank
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com
"""

Remember that the name string is the dictionary key and has to be unique.

Thanks
that was extremely helpful

Using the code you gave me, I modified it a bit to enable more easy user interaction, but I want a function to change an attribute of an entry, say the email.
heres the code so far

intro = "Welcome to Adress_Book.py"
name_dic = {}
loop = 1
menu_choice = 0

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)

def add_new():
    name = raw_input("Enter name: ")
    home = raw_input("Enter home: ")
    mobile = raw_input("Enter mobile: ")
    email = raw_input("Enter email: ")

    name_dic[name] = Data(home, mobile, email)

def printout():
    for key in name_dic:
        print( "Name = %s" % key )
        print( name_dic[key].get_info() )

def look_up():
    search = raw_input("Enter name to be searched: ")
    if name_dic.has_key(search):
        print( "Name = %s" % search )
        print( name_dic[search].get_info() )

    else:
        print( "Name %s not found" % search )

def del_entry():
    d_search = raw_input("Enter name to be deleted: ")
    if name_dic.has_key(d_search):
        del name_dic[d_search]
        print( "Name %s deleted" % d_search)

    else:
        print( "Name %s not found" % d_search )

def change_att():
    c_search = raw_input("Enter name to alter: ")
    if name_dic.has_key(c_search):
        c_name = raw_input("What element do you want to change: ")
        if c_name == 'email':
            n_e = raw_input("Enter new email adress: ")
            #n_e being the new email adress

so how can I take n_e and swap it for the old email adress

sorry my mistake :)

intro = "Welcome to Adress_Book.py"
name_dic = {}
loop = 1
menu_choice = 0

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)

def add_new():
    name = raw_input("Enter name: ")
    home = raw_input("Enter home: ")
    mobile = raw_input("Enter mobile: ")
    email = raw_input("Enter email: ")

    name_dic[name] = Data(home, mobile, email)

def printout():
    for key in name_dic:
        print( "Name = %s" % key )
        print( name_dic[key].get_info() )

def look_up():
    search = raw_input("Enter name to be searched: ")
    if name_dic.has_key(search):
        print( "Name = %s" % search )
        print( name_dic[search].get_info() )

    else:
        print( "Name %s not found" % search )

def del_entry():
    d_search = raw_input("Enter name to be deleted: ")
    if name_dic.has_key(d_search):
        del name_dic[d_search]
        print( "Name %s deleted" % d_search)

    else:
        print( "Name %s not found" % d_search )

def change_att():
    c_search = raw_input("Enter name to alter: ")
    if name_dic.has_key(c_search):
        c_name = raw_input("What element do you want to change: ")
        if c_name == 'email':
            n_e = raw_input("Enter new email adress: ")
            name_dic[c_search].email = n_e
        elif c_name == 'home':
            n_h = raw_input("Enter new home number: ")
            name_dic[c_search].home = n_h
        elif c_name == 'mobile':
            n_m = raw_input("Enter new mobile number: ")
            name_dic[c_search].mobile = n_m
    else:
        print( "Name %s not found" % c_search )

print intro

while loop != 0:
    print """
1) Add new entry
2) Remove an entry
3) Look up an entry
4) Print out adress book
5) Edit an entry
6) Exit
    """

    menu_choice = input("Enter choice: ")

    if menu_choice == 1:
        add_new()
    elif menu_choice == 2:
        del_entry()
    elif menu_choice == 3:
        look_up()
    elif menu_choice == 4:
        printout()
    elif menu_choice == 5:
        change_att()
    elif menu_choice == 6:
        loop = 0
    else:
        print "Please anter a valid option"

I want to write file I/O for this, having tried before and failed, so could someone pls point me in the right direction.

Let's say you want to change the email:

# a test setup

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data for testing
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'
name_dic[name] = Data(home, mobile, email)

# second set of data for testing
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'
name_dic[name] = Data(home, mobile, email)

def change_att():
    #c_search = raw_input("Enter name to alter: ")
    c_search = 'bob dork'  # for testing only!!!
    if name_dic.has_key(c_search):
        #c_name = raw_input("What element do you want to change: ")
        c_name = 'email'  # for tesing only!!!
        if c_name == 'email':
            #n_e = raw_input("Enter new email adress: ")
            n_e = 'bob.dork@yahoo.com'  # for testing only!!!
            # make the change
            k = name_dic[c_search]
            name_dic[c_search] = Data(k.home, k.mobile, n_e)

# get the info for all names added before change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

change_att()

# get the info for all names added after change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

"""
my output -->
Name = frank millato
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob dork
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com

----------------------------------------
Name = frank millato
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob dork
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@yahoo.com
"""

cheers, but do you have any ideas on pickleing this to create file io
especially regarding the load

Member Avatar for leegeorg07

I have to say that from python 2.5 and on you can use the 'a' file open method (append), which just adds to the data already in the file, i changed all of my programs to use this instead and it works so much faster

being fairly unfamiliar with such code, how would that be placed within my code to enable me to save and load the data.

Member Avatar for leegeorg07

I think the easiest way to explain it is to say its like a list where you would use:

mylist = []
mylist.append('hello')
print mylist
#outputs
['hello']

and in yours it would be something like:

people = open('people_data.txt', 'a')
class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data for testing
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'
name_dic[name] = Data(home, mobile, email)

# second set of data for testing
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'
name_dic[name] = Data(home, mobile, email)

def change_att():
    #c_search = raw_input("Enter name to alter: ")
    c_search = 'bob dork'  # for testing only!!!
    if name_dic.has_key(c_search):
        #c_name = raw_input("What element do you want to change: ")
        c_name = 'email'  # for tesing only!!!
        if c_name == 'email':
            #n_e = raw_input("Enter new email adress: ")
            n_e = 'bob.dork@yahoo.com'  # for testing only!!!
            # make the change
            k = name_dic[c_search]
            name_dic[c_search] = Data(k.home, k.mobile, n_e)

# get the info for all names added before change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

change_att()

# get the info for all names added after change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )
#and then after sowing it you can append it:
# get the info for all names added after change
for key in name_dic:
    if key not in people.read():
        people.write("Name = %s" % key)
        people.write(name_dic[key].get_info())

please bare in mind that what ive added i havent tested so take it with a pinch of salt

Member Avatar for leegeorg07

i just tested it and it had a couple of my errors so here is a fix:

people = open('people_data.txt', 'a')
people2 = open('people_data.txt', 'r')
class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data for testing
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'
name_dic[name] = Data(home, mobile, email)

# second set of data for testing
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'
name_dic[name] = Data(home, mobile, email)

def change_att():
    #c_search = raw_input("Enter name to alter: ")
    c_search = 'bob dork'  # for testing only!!!
    if name_dic.has_key(c_search):
        #c_name = raw_input("What element do you want to change: ")
        c_name = 'email'  # for tesing only!!!
        if c_name == 'email':
            #n_e = raw_input("Enter new email adress: ")
            n_e = 'bob.dork@yahoo.com'  # for testing only!!!
            # make the change
            k = name_dic[c_search]
            name_dic[c_search] = Data(k.home, k.mobile, n_e)

# get the info for all names added before change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

change_att()

# get the info for all names added after change
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )
#and then after sowing it you can append it:
# get the info for all names added after change
for key in name_dic:
    if key not in people2:
        people.write("Name = %s" % key)
        people.write(name_dic[key].get_info())

So how could I put this into my code - saving the contents of the dictionary, and reopeninging them later.

Member Avatar for leegeorg07

I did that in there but basically all it is that does it are 2 snippets:

people = open('people_data.txt', 'a')
people2 = open('people_data.txt', 'r')
#which opens 2 versions of the file, 1 to append and 1 to read to make sure the information is all unique
#and
for key in name_dic:
    if key not in people2:
        people.write("Name = %s" % key)
        people.write(name_dic[key].get_info())
#that checks for previous entries that are the same and then writes entries that aren't
#I cant really explain it, I'm going to have to rely on someone else to make it simple as the list example is my best attempt

OKay then, how would I place that in my code to solve the prblem?

I took the liberty to use sneekula's test setup ...

# a test setup for pickle dump and load
# note that pickle does not save the class itself
# if the dumped data file is used in another program,
# you need to code a matching class in that program

import pickle

class Data(object):
    def __init__(self, home, mobile, email):
        self.home = home
        self.mobile = mobile
        self.email = email
        self.get_info()

    def get_info(self):
        sf = \
"""Home Phone: %s
Mobile Phone: %s
Email: %s
"""
        return sf % (self.home, self.mobile, self.email)


name_dic = {}

# first set of data for testing
name = 'frank millato'
home = '123-456-7890'
mobile = '456-789-0123'
email = 'frank23@gmail.com'
name_dic[name] = Data(home, mobile, email)

# second set of data for testing
name = 'bob dork'
home = '234-567-8901'
mobile = '567-690-1234'
email = 'bob.dork@hotmail.com'
name_dic[name] = Data(home, mobile, email)

# get the info for all names before dump
print( "Original data:" )
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

print('-'*40)

fname = "PhoneDict.dat"
# pickle dump the dictionary
fout = open(fname, "w")
pickle.dump(name_dic, fout)
fout.close()

# delete the name_dic object
del name_dic

# pickle load the dictionary
fin = open(fname, "r")
name_dic = pickle.load(fin)
fin.close()

# get the info for all names after load
print( "Data dumped and reloaded with module pickle:" )
for key in name_dic:
    print( "Name = %s" % key )
    print( name_dic[key].get_info() )

"""
my output -->
Original data:
Name = frank millato
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob dork
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com

----------------------------------------
Data dumped and reloaded with module pickle:
Name = frank millato
Home Phone: 123-456-7890
Mobile Phone: 456-789-0123
Email: frank23@gmail.com

Name = bob dork
Home Phone: 234-567-8901
Mobile Phone: 567-690-1234
Email: bob.dork@hotmail.com
"""

Thanks guys, I'm all sorted now.
My comments on this page all sound the same right, well this sounds stupid, but i had no idea that the post had gon onto a second page therefore, I just assumed my post hadn't been posted, so i posted it again, sorry.

Member Avatar for leegeorg07

@vegaseat: just wondering, why did you use pickle? I found that using the append function of open works easier and faster

@vegaseat: just wondering, why did you use pickle? I found that using the append function of open works easier and faster

If you save the data as a text file like in your case, then you have to rebuild the entire dictionary each time when you load the saved data. As the size of the data grows, this gets to be time consuming. Also, if you edit the data and simply append to a text file, then the old data would still be there.

Member Avatar for leegeorg07

oh right ok, thanks, however for the replacement problem, could you just use a unique decision?

oh right ok, thanks, however for the replacement problem, could you just use a unique decision?

Don't quite understand what you mean with 'unique decision', can you give an example?

Member Avatar for leegeorg07

well the simplest version for unique is to use a set where you would incorporate both of them in a set making sure the new information is first like:

mydata = ['hello', 'test', 'change']
mynewdata = ['hello', 'test', 'change']
myset = set(mynewdata, mydata)

although having thought of that it would be better to use

file = open('filename', 'r+')

so that you will overwrite it, but you can still read it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.