There is an excel table: enter image description here

Trying to write data to the dictionary:

from openpyxl import Workbook, load_workbook wb = load_workbook('Таблица исключений.xlsx') sheet_ranges = wb['Лист1'] for row in sheet_ranges.iter_rows(row_offset=0): a = row[0].value c = row[1].value b = {} b[a] = c print(b) 

I receive:

 Р ЛЬВОВИЧ': 10003359} {'МОКРОУСОВА ОЛЬГА АНАТОЛЬЕВНА': 10003360} {'НАГЛЕНКО ВАЛЕРИЙ ВЛАДИМИРОВИЧ': 10003361} 

I do not understand why the data is not displayed all? And when I try to get the value:

 print(b['МОКРОУСОВА ОЛЬГА АНАТОЛЬЕВНА']) 

There is an error:

 KeyError: 'МОКРОУСОВА ОЛЬГА АНАТОЛЬЕВНА' 

Can you please tell me how to fix the situation? Thanks in advance for your reply.

    1 answer 1

    Because the dictionary is recreated every time:

     for row in sheet_ranges.iter_rows(row_offset=0): b = {} # пусто!!! b[a] = c # всегда хранит только (последнее) одно значение 

    Why not take it out for the cycle ?!

     b = {} # до цикла for row in sheet_ranges.iter_rows(row_offset=0): b[a] = c print(b) # после цикла 
    • Thank you very much. Everything worked !!! - Ireen1985