-1

I read one xlsx file in this i have two sheets and i want store in a dictionary of tuples but at the end of the tuples, I got extra comma.

my output: data_dict = {"sheet1":[('A',), ('B',), ('C',), ('D',)],"sheet2":[('A',), ('B',), ('C',), ('D',)]}

the correct output I want:
data_dict = {"sheet1":[('A'), ('B'), ('C'), ('D')],"sheet2":[('A'), ('B'), ('C'), ('D')]}

My current code is

    import openpyxl
    wb = load_workbook(xlsx_filename)
    #print(wb)
    data_dict = {}
    for sheet in wb:
        #print(sheet)

        data_dict[sheet.title] = []
        for row in sheet.rows:
            #print(sheet.rows)
            row_wise_data = tuple([cell.value for cell in row])
            data_dict[sheet.title].append(row_wise_data)
    #print(data_dict)  # result in dictionary

    return data_dict
    wb.close()
  • What happens when you remove the `tuple()` conversion? Do you get an acceptable output? – quamrana Oct 17 '20 at 16:12
  • 3
    You are running Python, so the output you get is Python as well. A tuple with a single value needs to be with a comma. Otherwise it could be confused with a mathematical brace that defines operator precedence. Why do you want the output to be different? Do you need to process it in some other application? Then print() is not the right way. – Thomas Weller Oct 17 '20 at 16:13
  • You are reading your data from a xlsx file. What delimiters do you have? Are you sure your comma doesn't come from that? – Serge de Gosson de Varennes Oct 17 '20 at 16:34

1 Answers1

0

Split the comma out in your list comprehension:

row_wise_data = tuple([cell.value.split(',')[0] for cell in row])
Tyler
  • 143
  • 9