sonali
sonali

Reputation: 229

Storing multiple values into Dictionary

I am new to python and am facing difficulties in dictionary. I am trying to store multiple values from excel into dictionary.

This is my input:

enter image description here

And i am trying to store in this way.

My expected output is:

d = [
{
"name":"dhdn",
"sub":["c","java","python"]
},
{
"name":"subbu",
"sub":["java","perl"]
}
]

I tried like this:

df_service = pd.read_excel(existing_excel_file, sheet_name='Sheet1')
df_service = df_service.replace(np.nan, "dummy")
print(df_service)

list1 = []

for i in range(0, len(df_service['name'])):
    dict1 = {}
    lst = []
    if df_service['name'][i] != 'dummy':        
        dict1["name"] = df_service['name'][i]
        lst.append(df_service['sub'][i])
    else:
        lst.append(df_service['sub'][i])
    dict1["sub"] = lst
    list1.append(dict1)

print(list1)

And what if the excel data is like given below:

enter image description here

What if we have data like this? How to create a dictionary for this?

Need some suggestion, not getting any idea.

Upvotes: 1

Views: 79

Answers (3)

Dhananjaya D N
Dhananjaya D N

Reputation: 357

df_service = df_service.fillna(method='ffill')
result = [{'name':k[0],'usn':k[1],'sub':v["sub"].tolist(),"marks":v["marks"].tolist()} for k,v in df_service.groupby(['name', 'usn'])]
pprint (result)

Upvotes: 1

Dhananjaya D N
Dhananjaya D N

Reputation: 357

enter image description here

Hi @ncica, I appreciate your answer, what if we have data like this? How to create a dictionary for this.

Upvotes: 1

ncica
ncica

Reputation: 7206

You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward.

df_service = pd.read_excel(existing_excel_file, sheet_name='Sheet1')

df_service = df_service.fillna(method='ffill')
result = [{'name':k,'sub':g["sub"].tolist()} for k,g in df_service.groupby("name")]
print (result)

output:

[{'name': 'dhdn', 'sub': ['c', 'java', 'python']}, {'name': 'subbu', 'sub': ['java', 'perl']}]

Upvotes: 1

Related Questions