Python Forum
Trouble displaying items from lists
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble displaying items from lists
#1
So I am writing a code for an address book. I have a function that searches for a nickname of a person then prints their details if the nickname is in the list but I only getting the "contact does not exist" every time I run this Please help! also P.S does anyone have any good resources on turning lists into dictionaries? Cheers

import sys
Numbers=[]
Names=[]
nicknames=[]
address=[]


def addcontact():
        print ("-------------")
        print ("Adding a Contact\n-------------")
        name = input("Enter first and last name :").lower
        Names.append(name)
        nickname = input("Enter the nickname").lower
        nicknames.append(nickname)
        number = input("Enter number :")
        Numbers.append(number)
        Addres = input("Enter the address").lower
        address.append(Addres)
        print("***Contact added succesfully***")
        menu()

def searchcontact():
        print ("\nSearch Contact by Nickname\n--------------------")
        nick = input("Please enter the nicnkname")
        if nick in nicknames:
            print ("The Contacts are listed Below")
            print ("-----------------------------")
            index = nicknames.index(nick)
            print ("\n", nicknames[index])
            print ("\n",Names[index])
            print ("\n",address[index])
            print ("\n", Numbers[index])
        elif nick not in nicknames:
            print ("\nThis Contact Does Not Exist!!\n----------------------\n")
        menu()

def showcontact():
        for i in range(len(Names)):
            print (str(Names[i]) + "........"+ str(Numbers[i]))
        #print Names
        #print Numbers
        print ("--------------------")

def quit():
        print("Exiting....")
        sys.exit


def menu():
        print ("---------------------------------------")
        print  ("***Welcome to the Python address book***\n"+
                "\n----------------------------------------"+
                "\n| 1 | To Add Contact"+
               "\n| 2 | To search for the Contact by nickname\n| 3 | To list all contacts in the address book\n| 4 | To quit\n"+
                "----------------------------------------\n>")
menu()
while True:
        selection = input("Please Select:")
        if selection =='1':
            addcontact()
        elif selection =='2': searchcontact()
        elif selection =='3': showcontact()
        elif selection == '4': quit()
        else:
            print ("Unknown Command")
menu()
selection = input("Please Select:")
---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | To Add Contact
| 2 | To search for the Contact by nickname
| 3 | To list all contacts in the address book
| 4 | To quit
----------------------------------------
>
Please Select:1
-------------
Adding a Contact
-------------
Enter first and last name :John Doe
Enter the nicknameJohnny
Enter number :123456789
Enter the address123 Hello World street
***Contact added succesfully***
---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | To Add Contact
| 2 | To search for the Contact by nickname
| 3 | To list all contacts in the address book
| 4 | To quit
----------------------------------------
>
Please Select:2

Search Contact by Nickname
--------------------
Please enter the nicnknameJohnny

This Contact Does Not Exist!!
----------------------

---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | To Add Contact
| 2 | To search for the Contact by nickname
| 3 | To list all contacts in the address book
| 4 | To quit
----------------------------------------
>
Please Select:
Reply
#2
for list to dict checkout:
from collections import defaultdict example here: http://stackoverflow.com/questions/42824...-as-values
Reply
#3
Thanks man I will check that out. Funny I have run into an entirely new problem now

I am trying to write a delete function that asks the user for the nickname they want to delete then deletes the contact details associated with that nickname however I have two problems.

1. When my program goes to print
reply = input("Delete Contact? "+str(Names)+"? [y/[n]] ")
It shows every contact that is in the addressbook not the one that I want to be deleted

and 2.

How do I go about actually deleting an item from the list I dont think this function is written correctly and I would really really appreciate the help as I have a sh*tload of work to get through this month XD

def deletecontact():
           z = input('Who would you like to delete (Enter nickname):')
           for nick in nicknames:
                    if z in nicknames:
                       reply = input("Delete Contact? "+str(Names)+"? [y/[n]] ")
           if z not in nicknames:
                   print ("\nThis Contact Does Not Exist!!\n----------------------\n")
                   if reply=='y':
                       del z
                       print('Contact has been DELETED')
           menu()
Cheers in adv :)
Reply
#4
It looks as if names is a list.
try print(names) to see.
if so, you can find the index of the one you want by using index
idx = nicknames.index('nick')
del nicknames[idx]
not tested, but should be OK
Reply
#5
(May-18-2017, 04:37 AM)Larz60+ Wrote: It looks as if names is a list.
try print(names) to see.
if so, you can find the index of the one you want by using index
idx = nicknames.index('nick')
del nicknames[idx]
not tested, but should be OK
Yeah names is part of a list that has been put into a dictionary (thanks to your previous post xD)

So I have written
def deletecontact():
            delname = input('Who would you like to delete (Enter nickname):')
            for nick in nicknames:
                if delname in nicknames:
                    reply = input("Delete Contact? "+str(Names)+"? [y/[n]] ")
                    if delname not in nicknames:
                        print ("This Contact Does Not Exist!!\n----------------------\n")
                if reply=='y':
                        idx = nicknames.index(delname)
                        del nicknames[idx]
                        print('Contact has been DELETED')
            menu()
That seems to have done it using the index method :)

Now I just need to print a message to tell the user that there are no contacts listed if they go to show contacts and nothing is in the list because if I do that now I get this error 
    print ("--------------------" + "\n" + str(nicknames[i]) + "\n" + str(Names[i]) + "\n"  +  str(Numbers[i]) + "\n"  +  str(address[i]) + "\n" + "--------------------")

IndexError: list index out of range

Not too sure but I may have figured it out and I really do apologize if I butcher this explanation

So I can save contacts just fine and print them that is cool but when I go to delete a contact (by searching its nickname) then again call the function to show the list of contacts it throws up the

IndexError: list index out of range
To explain this here is the input and output:
import sys
Numbers=[]
Names=[]
nicknames=[]
address=[]
from collections import defaultdict

x = [Numbers, Names, nicknames, address]
len_dict = defaultdict(list)
for word in x:
   len_dict[len(word)].append(word)
len_dict

def addcontact():
       print ("-------------")
       print ("Adding a Contact\n-------------")
       name = input("Enter first and last name :")
       Names.append(name)
       nickname = input("Enter the nickname")
       nicknames.append(nickname)
       number = input("Enter number :")
       Numbers.append(number)
       Addres = input("Enter the address")
       address.append(Addres)
       print("***Contact added successfully***")
       menu()

def searchcontact():
       print ("\nSearch Contact by Nickname\n--------------------")
       nick = input("Please enter the nicnkname")
       for nick in nicknames:
               if nick in nicknames:
                   print ("The Contacts are listed Below")
                   print ("-----------------------------")
                   index = nicknames.index(nick)
                   print ("\n", nicknames[index])
                   print ("\n",Names[index])
                   print ("\n",address[index])
                   print ("\n", Numbers[index])
       if nick not in nicknames:
               print ("\nThis Contact Does Not Exist!!\n----------------------\n")
       menu()

def showcontact():
       for i in range(len(Names)):
           print ("--------------------" + "\n" + str(nicknames[i]) + "\n" + str(Names[i]) + "\n"  +  str(Numbers[i]) + "\n"  +  str(address[i]) + "\n" + "--------------------")
       menu()

def deletecontact():
           delname = input('Who would you like to delete (Enter nickname):')
           for nick in nicknames:
               if delname in nicknames:
                   reply = input("Delete Contact? "+str(Names)+"? [y/[n]] ")
                   if delname not in nicknames:
                       print ("This Contact Does Not Exist!!\n----------------------\n")
               if reply=='y':
                       idx = nicknames.index(delname)
                       del nicknames[idx]
                       print('Contact has been DELETED')
           menu()

def quit():
       print("Exiting....")
       sys.exit


def menu():
       print ("---------------------------------------")
       print  ("***Welcome to the Python address book***\n"+
               "\n----------------------------------------"+
               "\n| 1 | Add Contact"+
              "\n| 2 | To search for the contact by nickname\n| 3 | To list all contacts in the address book\n| 4 | Delete Contact\n| 5 | Quit"+"\n"
               "----------------------------------------\n")
menu()

while True:
       selection = input("Please Select :")
       if selection =='1': addcontact()
       elif selection =='2': searchcontact()
       elif selection =='3': showcontact()
       elif selection == '4': deletecontact()
       elif selection == '5': quit()
       else:
           print ("Unknown Command")
           menu()
selection = input("Please Select:")
And then the output:

---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | Add Contact
| 2 | To search for the contact by nickname
| 3 | To list all contacts in the address book
| 4 | Delete Contact
| 5 | Quit
----------------------------------------

Please Select :1
-------------
Adding a Contact
-------------
Enter first and last name :John Doe
Enter the nicknameJohnny
Enter number :333-000-000
Enter the address55 Hello Street
***Contact added successfully***
---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | Add Contact
| 2 | To search for the contact by nickname
| 3 | To list all contacts in the address book
| 4 | Delete Contact
| 5 | Quit
----------------------------------------

Please Select :1
-------------
Adding a Contact
-------------
Enter first and last name :Tom Hanks
Enter the nicknameHanky
Enter number :321-000-000
Enter the address123 Red Street
***Contact added successfully***
---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | Add Contact
| 2 | To search for the contact by nickname
| 3 | To list all contacts in the address book
| 4 | Delete Contact
| 5 | Quit
----------------------------------------

Please Select :4
Who would you like to delete (Enter nickname):Hanky
Delete Contact? ['John Doe', 'Tom Hanks']? [y/[n]] y
Contact has been DELETED
---------------------------------------
***Welcome to the Python address book***

----------------------------------------
| 1 | Add Contact
| 2 | To search for the contact by nickname
| 3 | To list all contacts in the address book
| 4 | Delete Contact
| 5 | Quit
----------------------------------------

Please Select :3
--------------------
Johnny
John Doe
Traceback (most recent call last):
333-000-000
 File "C:/Users/LiquidO/Desktop/Semester 1 I.T/Python/a2/a3q2test.py", line 81, in <module>
55 Hello Street
   elif selection =='3': showcontact()
--------------------
 File "C:/Users/LiquidO/Desktop/Semester 1 I.T/Python/a2/a3q2test.py", line 47, in showcontact
   print ("--------------------" + "\n" + str(nicknames[i]) + "\n" + str(Names[i]) + "\n"  +  str(Numbers[i]) + "\n"  +  str(address[i]) + "\n" + "--------------------")
IndexError: list index out of range

Process finished with exit code 1
Reply
#6
Because you only delete things from Nicknames, so Names has more elements than Nicknames and you are using an index of Names to iterate things in Nicknames.

Incidentally, keeping "parallel arrays" like this is a well-known anti-pattern (you problem above is exactly one of the frequent pitfalls) and you should really be using a single array of "aggregates" that contain the Nickname, Name, and other information for each person in the address book.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#7
Quote:Incidentally, keeping "parallel arrays" like this is a well-known anti-pattern (you problem above is exactly one of the frequent pitfalls) and you should really be using a single array of "aggregates" that contain the Nickname, Name, and other information for each person in the address book.


Do you happen to have any reference material that explains how to perform this?  My task outline states I need to use a dictionary and what I've done is just convert the lists (Names,nicknames,Numbers,address) into the one dictionary (not sure if that is even correct in the code either xD)
Reply
#8
see 8.3.3.1 using default dict from single list: https://docs.python.org/2/library/collections.html
Reply
#9
(May-18-2017, 07:37 AM)Liquid_Ocelot Wrote:
Quote:Incidentally, keeping "parallel arrays" like this is a well-known anti-pattern (you problem above is exactly one of the frequent pitfalls) and you should really be using a single array of "aggregates" that contain the Nickname, Name, and other information for each person in the address book.


Do you happen to have any reference material that explains how to perform this?  My task outline states I need to use a dictionary and what I've done is just convert the lists (Names,nicknames,Numbers,address) into the one dictionary (not sure if that is even correct in the code either xD)

I don't see any useful dictionary in your code. I would expect a dictionary where nicknames are the keys, and the values are tuples with name, address, and phone number. In other words, your code should have something like:

# Add the person:
persons[nickname]=(name,address,phone)

# Search the person:
if nickname in persons:
    name,address,phone=persons[nickname]
    print nickname, name, address, phone
else:
   print "Not found"
Look ma, no arrays!
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  QUERY on Looping and creating lists as items within dictionaries ajayachander 3 2,276 Mar-26-2020, 02:03 PM
Last Post: ajayachander
  Trouble in lists erfanakbari1 2 2,280 Feb-26-2019, 08:46 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020