Reputation: 229
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:
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:
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
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
Reputation: 357
Hi @ncica, I appreciate your answer, what if we have data like this? How to create a dictionary for this.
Upvotes: 1
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