Home > Software design >  Creating a dictionary from a dataframe
Creating a dictionary from a dataframe

Time:09-17

enter image description here

you can use the below code.

import os
import  pandas as pd

# create a empty dictionary
dict = {}

# read the data from the dataframe
df = pd.read_excel(r'C:\*********\Output.xlsx')

# itterate through the DF
for index in df.index:

    # initialize key vairiable with ID columns
    key = df['ID'][index]

    # if key alreadt exists the append the value which is in list format for else starting 
    # adding values into a list
    if key in dict:
        dict[key].append(df['Medicine Name'][index])
    else:    
        dict[key] = [df['Medicine Name'][index]]


print(dict)

Output Dictionary

{53: ['A', 'B', 'C', 'D', 'E', 'F'], 
54: ['G', 'H', 'I', 'J', 'K'], 
55: ['L', 'M']}
  • Related