You have a nice start there. The hard part for me when solving this problem for myself was figuring out how to chunk the rows into pairs.
Here are two solutions to this problem. The first one might be a little easier conceptually to see what is going on. And then I discovered a very slick way to chunk things using itertools.zip_longest
. See How to chunk a list in Python 3?
import urllib.request
import xlrd
import itertools as it
# Fake data stored on my Minio server.
url = "https://minio.apps.selfip.com/mymedia/xlxs/fake_xl.xlxs"
filepath, response = urllib.request.urlretrieve(url, "/tmp/test.xlxs")
wb = xlrd.open_workbook(filepath)
ws = wb.sheet_by_index(0)
odd_rows, even_rows = it.tee(ws.get_rows()) # Get 2 iterables using itertools.tee
row_pairs = ( # generator expression to "chunk the rows into groups of 2"
[[cell.value for cell in row] for row in rows] # 2D list of values
for rows in zip(
it.islice(odd_rows, 0, ws.nrows, 2), # Use itertools.islice, odd
it.islice(even_rows, 1, ws.nrows, 2), # even
)
)
# zip is useful for "zipping" key value pairs together.
print([dict(zip(*row_pair)) for row_pair in row_pairs])
# Another way to chunk the rows into pairs is like this:
print([
dict(zip(*[[cell.value for cell in pair] for pair in pairs]))
for pairs in it.zip_longest(*it.repeat(iter(ws.get_rows()), 2))
])
Ouput for both:
[{'2a5de626': 'algorithm', '86ce99a2': 'implementation', 'e6b481ba': 'adapter', 'bc85c996': 'capability', '4edfb828': 'array', '05d79ce2': 'definition', 'b9b5ae33': 'knowledgebase', 'f0da7366': 'complexity', '39a48259': 'methodology', '1ee95d9e': 'strategy'}, {'01bc389d': 'neural-net', 'd5d16b0c': 'monitoring', 'd9fb3a8d': 'installation', '8c7a049f': 'moratorium', 'f3d9aa0e': 'help-desk', 'd0e8d371': 'paradigm', '9e33f679': 'complexity', '6354affc': 'core', '606c4eb6': 'groupware', '97741196': 'strategy'}, {'76ae32df': 'algorithm', '942654da': 'task-force', '462fa31b': 'ability', '584df007': 'adapter', 'f6293960': 'attitude', 'afd8fa00': 'knowledgebase', '4c5f2c49': 'alliance', '6d76c690': 'collaboration', '3018a22b': 'solution', '034f1bb2': 'access'}]