Question

I've been trying to add the number of 2 list inside a dictionnary. The thing is, I need to verify if the value in the selected row and column is already in the dictionnary, if so I want to add the double entry list to the value (another double entry list) already existing in the dictionnary. I'm using a excel spreadsheet + xlrd so i can read it up. I' pretty new to this.

For exemple, the code is checking the account (a number) in the specified row and columns, let's say the value is 10, then if it's not in the dictionnary, it add the 2 values corresponding to this count, let's say [100, 0] as a value to this key. This is working as intended.

Now, the hard part is when the account number is already in the dictionnary. Let's say its the second entry for the account number 10. and it's [50, 20]. I want the value associated to the key "10" to be [150, 20].

I've tried the zip method but it seems to return radomn result, Sometimes it adds up, sometime it doesn't.

import xlrd
book = xlrd.open_workbook("Entry.xls")
print ("The number of worksheets is", book.nsheets)
print ("Worksheet name(s):", book.sheet_names())
sh = book.sheet_by_index(0)
print (sh.name,"Number of rows", sh.nrows,"Number of cols", sh.ncols)
liste_compte = {}
for rx in range(4, 10):
    if (sh.cell_value(rowx=rx, colx=4)) not in liste_compte:
        liste_compte[((sh.cell_value(rowx=rx, colx=4)))] = [sh.cell_value(rowx=rx, colx=6), sh.cell_value(rowx=rx, colx=7)]
    elif (sh.cell_value(rowx=rx, colx=4)) in liste_compte:
        three = [x + y for x, y in zip(liste_compte[sh.cell_value(rowx=rx, colx=4)],[sh.cell_value(rowx=rx, colx=6), sh.cell_value(rowx=rx, colx=7)])]
        liste_compte[(sh.cell_value(rowx=rx, colx=4))] = three
print (liste_compte)
Was it helpful?

Solution

I'm not going to directly untangle your code, but just help you with a general example that does what you want:

 def update_balance(existing_balance, new_balance):
     for column in range(len(existing_balance)):
         existing_balance[column] += new_balance[column]


 def update_account(accounts, account_number, new_balance):
     if account_number in accounts:
        update_balance(existing_balance = accounts[account_number], new_balance = new_balance)
     else:
        accounts[account_number] = new_balance

And finally you'd do something like (assuming your xls looks like [account_number, balance 1, balance 2]:

  accounts = dict()
  for row in xls:
      update_account(accounts       = accounts, 
                     account_number = row[0],
                     new_balance    = row[1:2])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top