문제

I am trying to write a program that loads an excel file into a dictionary in Python. I am having trouble trying to find out how to proceed. I know how to load a single value to a key, but this file has more than one value assigned to each key. What would the code for this look like? Let's say everything in column A of the excel file is a name, and everything in columns B, C, and D pertain to each name in A. I want A to be the key and B, C, and D to be the values.

도움이 되었습니까?

해결책

From your description, the following code would works:

import csv

# Result dictionary
result = {}
# Open the file in Universal mode
with open('Fruit.csv', 'rU') as f:
    # Get the CSV reader and skip header
    reader = csv.reader(f)
    reader.next()

    for row in reader:
       #First column is the key, the rest is value
       result[row[0]] = row[1:]

UPDATED: If you need to verify running result, replace the for block with this:

    for row in reader:
       #First column is the key, the rest is value
       result[row[0]] = row[1:]
       # Print row
       print row
       # Print result
       print row[0], ':', result[row[0]]

다른 팁

I think the following steps will do this work:

  1. open MS excel.
  2. read column names in excel file, as you may read data in that column, I guess what you really need is index of that column.
  3. treat value in the first column (I suppose it should be 'A') as key and other columns as value (by the way, 'A' doesn't need to be the first column as you could search in Excel row).

For step1, may get help from xlrd

For step2, please reference the following code:

    # read excel and get appropriate sheet
    rb = xlrd.open_workbook(filename, on_demand=True, formatting_info=True)
    my_sheet = rb.sheet_by_name(u'template name')

    # get column names in item_list        
    item_list = my_sheet.row_values(1)
    nrows = my_sheet.rows
    ncolumns = my_sheet.columns
    key_index = item_list.index('A')
    value_index = item_list.index('B') # of course 'C' and 'D' if needed

For step3, may use index to get value in each row

    for row in nrows:
        key = my_sheet[row][key_index]
        ....

Please see my application if needed, it isn't same but maybe related with python excel usage, hope helpful.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top