inspiring
inspiring

Reputation: 123

How do I convert an excel file into a nested python dictionary?

I have a very specific Excel sheet that looks like this:

Excel Sheet Picture

I am trying to convert it to a Python dictionary like this:

item_map = {
    "1609755": {
        "name": "test 1",
        "price": 125,
        "check_type": "check 1"
    },
    "1609756": {
        "name": "test 2",
        "price": 2500,
        "check_type": "check 2"
    },
    "1609758": {
        "name": "test 3",
        "price": 2400,
        "check_type": "check 3"
    }
}

My question is: How do I convert a excel sheet to a Python dictionary?


So far I tried using the library sheet2dict and also pandas, however in the excel sheet, the id is a key in the dictionary. As a result, I am quite stumped on how to ensure that the first column is ALWAYS set as a key.

from sheet2dict import Worksheet
ws = Worksheet()
file_path = 'test.xlsx'

x = ws.xlsx_to_dict(path = file_path)

print(x)

Upvotes: 3

Views: 164

Answers (1)

Shivam Roy
Shivam Roy

Reputation: 2061

Since I do not have the Excel file, I created the DataFrame using your dictionary mentioned in the question i.e, item_map likewise:

df = pd.DataFrame(item_map).T    #Had to take a Transpose
df.index.name = 'id'

You can import your table as a DataFrame using pandas.read_excel. Remember to set the index as 'id'.

df = pd.read_excel('file_path')
df.index.name = 'id'

Then, use this code:

item_map = {}

for index, row in list(df.iterrows()):
    item_map[index] = dict(row)

print(item_map)

Output:

{'1609755': {'name': 'test 1', 'price': 125, 'check_type': 'check 1'},
'1609756': {'name': 'test 2', 'price': 2500, 'check_type': 'check 2'},
'1609758': {'name': 'test 3', 'price': 2400, 'check_type': 'check 3'}}

Upvotes: 1

Related Questions