louis
louis

Reputation: 635

openpyxl Fetch value from excel and store in key value pair

Have written a python script that fetches the cell values and displays in a list row by row.

Here is my script:

 book = openpyxl.load_workbook(excel_file_name)
 active = book.get_sheet_by_name(excel_file_name)

 def iter_rows(active): 
     for row in active.iter_rows(): 
         yield [cell.value for cell in row]

 res = list(iter_rows(active))
 for new in res:
     print new

Output for the above script: [state, country, code] [abc, xyz, 0][def, lmn, 0]

I want output in below format: [state:abc, country:xyz, code:0][state:def, country:lmn, code:0]

Please note: I want to do this from openpyxl

Upvotes: 0

Views: 2326

Answers (1)

Mike Müller
Mike Müller

Reputation: 85592

Try this:

res = iter_rows(active)
keys = next(res)
for new in res:
    print dict(zip(keys, new))

res is an iterator. Therefore, next(res) gives the next element. In our case the keys for the dictionary. Iterating through the rest of reswith the for loop, dict() creates a new dictionary for every element new using the same keys for all dictionaries. The function zip() combines two (or more) sequences in such a way, that it creates pairs with one element from each sequence. dict() uses one of these pairs as key and value for one new item and goes through of all pairs. For example, this:

dict(zip('abc', [1, 2, 3]))

results in this dictionary:

{'a': 1, 'b': 2, 'c': 3}

Upvotes: 2

Related Questions