Search code examples
pythondataframedictionarydata-science

Creating a dictionary from a dataframe


dataframe img I want to map the retail_store_id with the medicine name, by creating a dictionary where 53 i.e the retail_store_id is the key and the values will be the corresponding medicine name.

dict = { '53': ['PAN 40MG TAB', 'MOXIKIND CV 625MG TAB'.....]}      

Solution

  • I have considered the below dataset as example

    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')
    
    # iterate over 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']}