How to read specific item in a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • emokoena
    New Member
    • Aug 2011
    • 3

    How to read specific item in a list

    I have created a list and would like to read specific items in it, I only can read 1

    Code:
    import cPickle, sys, shelve
    
    ## open file that stores scores
        
    choice = None
    employees = []
    while choice != "0":
    
        print \
                """
                411 TUCKSHOP
    
                OPTIONS:
                0 - Exit
                1 - Employee: Add New Employee
                2 - Employee: Display Balance
                3 - Show All Employees and Balances
                4 - Employee: Make deposit
                5 - Purchase items @ Tuck Shop
                6 - Remove all emmployees from database
    
                """
        choice = raw_input("Choice: ")
        print
    
        #exit if choice is "0"
        if choice == "0":
            print "Good bye, please call again..."
    
        #Choice 1 - Add Employees to a file    
        elif choice == "1":
            #Create a sequence
            empnum = int(raw_input("Enter Employee Number: " ))
            name = raw_input("Enter Employee Name:" )
            sname = raw_input("Enter Employee Surname:" )
            dept = raw_input("Enter Department:" )
            bal = float(raw_input("Employee Balance R: "))
            entry = (empnum, name, sname, dept, bal)
            employees.append(entry)
            
            #create pickle file
            pickle_file = open("emp_data.dat", "a+")
            cPickle.dump(entry, pickle_file)
            #close pickle file
            pickle_file.close()
       
            #create a shelve
            #empshelve = shelve.open("emp_data2.da")
            #empshelve ["emp_number"] = [emp_number]
            
            #Ensure sync
            #empshelve.sync()
            #close shelve
            #empshelve.close()
    
        #Choice 2 - Display Balances
        elif choice == "2":
            
            pickle_file = open("emp_data.dat", "r")
            emps = cPickle.load(pickle_file)
            #Prompt user for search
            for entry in employees:
                empnum, name, sname, dept, bal = entry
            print name, "\t", bal
            empn = int(raw_input("\nChoose employee number: "))
            
            print "\nDisplaying Balance\n"
            if empn in emps:
                print "Balance ==> R ", emps[4] 
            else:
                print "Sorry"
            pickle_file.close()
    Last edited by Niheel; Aug 18 '11, 07:48 AM.
  • milesmajefski
    New Member
    • Aug 2011
    • 10

    #2
    In Python 3 the print statement is gone, it is replaced by the print function.

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      You have to check the first element of the tuple against the entry number:
      Code:
              found = False
              for entry in employees:
                  if empn == entry[0]:
                      print "Balance ==> R ", entry[4]
                      found = True
              if not found:
                  print "Not a valid employee number"
      Generally, a dictionary is used, with the employee number as the key pointing to a list of items http://greenteapress.com/thinkpython/html/book012.html so you can then use, if empn in employee_dict.

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        A couple of hints:
        # 6 is easy --> employees = [] ## re-initialize as an empty list
        When adding an employee, check if the number is already in the list, since you don't want the same employee number in the list twice.
        Use a function to look up an employee number, since you will be doing this for every choice on the menu.
        Use a list instead of a tuple so you can change it (make deposits)
        Read the pickle file once, before the while loop, instead of every time through the loop, and write/dump/close it once, after the while loop. Adds will be appended to the list that will be pickled.

        Comment

        • emokoena
          New Member
          • Aug 2011
          • 3

          #5
          All your suggestions have been invaluable and I have gotten someway but when I cPickle the file I fail to read the contents back as a list
          Code:
          #Choice 2 - Display Balances
              elif choice == "2":
                  
                  lists = []
                  infile = open('emp_data.dat', 'r')
                  #inlist = cPickle.load(infile)
                  while 1:
                      try:
                          lists.append(cPickle.load(infile))
                          
                      except (EOFError):
                          break
                  infile.close()
                  #Prompt user for search
                  print len(lists)
                  empn = int(raw_input("\nChoose employee number: "))
                  found = False 
                  for entry in lists: 
                     if empn == entry[0]: 
                          print "Balance ==> R ", entry[4] 
                          found = True 
                  if not found: 
                      print "Not a valid employee number"
          Last edited by bvdet; Aug 27 '11, 02:47 PM. Reason: Add code tags

          Comment

          • dwblas
            Recognized Expert Contributor
            • May 2008
            • 626

            #6
            It should be
            lists = cPickle.load(in file)

            Comment

            • emokoena
              New Member
              • Aug 2011
              • 3

              #7
              hi dwblas;

              I'm really am loosing my mind now. my code is only able to display the first entry, from there my if statement only evaluates to false for all other entries. please correct my code:

              #Choice 2 - Display Balances
              elif choice == "2":

              lists = []
              infile = open('emp_data. dat', 'r')
              lists = cPickle.load(in file)

              empn = int(raw_input(" \nChoose employee number: "))
              found = False
              for entry in lists:
              if empn == entry[0]:
              print "Balance ==> R ", entry[4]
              found = True
              if not found:
              print "Not a valid employee number"
              infile.close()

              Comment

              • dwblas
                Recognized Expert Contributor
                • May 2008
                • 626

                #8
                The pickle statement is still wrong. The link in my previous post shows an example of pickling and unpickling. If you are not going to read the post then there is little reason to post. Also, for future problems add a print statement. In this case:
                Code:
                for entry in lists:
                    print "testing" empn, entry[0]
                    if empn == entry[0]:
                please correct my code
                That's just rude.

                Comment

                Working...