Search code examples
pythonexceldictionaryxlrd

Using python and xlrd, what is the best way to read 2 columns from a spreadsheet


I have an excel spreadsheet that has 2 columns. Something like this

|ColA | ColB |
|Key | Value |
|1 | test |
|2 | test2 |
|3 | test4 |

and I want to read these two columns into a dictionary. I currently have this working but can't figure out how to extract out each key value pair

  sh = wb.sheet_by_index(0)
  for rownum in range(sh.nrows):
      print sh.row_values(rownum)

Solution

  • You're very close. If you want to build a dictionary from the a sheet that only contains keys and values, in the first two columns, you can simply do

    print dict(sh.row_values(rownum) for rownum in range(sh.nrows))
    

    As John Y mentioned, if you need to extract two specific columns with indexes i (keys) and j (values), you can do instead:

    print dict((sh.cell_value(rownum, i), sh.cell_value(rownum, j)) for rownum in range(sh.nrows))
    

    The key point is that dict() can build a dictionary from an iterable of (key, value) tuples.