Reputation: 83
I have a CSV file with rows ordered like this.
Table in text
0 | EST | Monday | Tuesday | Wednesday |
---|---|---|---|---|
1 | 12:00AM | Starting | ||
2 | 7:00PM | Prayer | Game Night | |
3 | 8:00PM | Board game | Ask anything |
I'm trying to create a nested Dictionary so that when someone asks for a Day (eg: Monday), all the events happening that day together with the time would be produced.
my_dict = {'Monday':{'EST':'7:30: PM', 'Event': 'Prayer Meeting', 'EST':'8:00: PM', 'Event': 'Board Game',}}
If a nested dictonary is not the right way, please guide me.
Upvotes: 1
Views: 52
Reputation: 862841
when someone asks for a Day (eg: Monday), all the events happening that day together with the time would be produced.
I think then dictionary should looks different:
First use DataFrame.melt
for unpivot and then remove rows with missing values by DataFrame.dropna
, last use DataFrame.groupby
in dict comprehension and create nested dictionaries:
df1 = df.melt('EST').dropna(subset=['value'])
d = {k: dict(zip(v['EST'], v['value'])) for k, v in df1.groupby('variable')}
print (d)
{'Monday': {'7:00PM': 'Prayer', '8:00PM': 'Board game'},
'Tuesday': {'12:00AM': 'Starting', '8:00PM': 'Ask anything'},
'Wednesday': {'7:00PM': 'Game Night'}}
Another alternative with different ouput - for each day are create lists of dictionaries - in dict comprehension is used DataFrame.to_dict
:
df1 = df.melt('EST', value_name='event').dropna(subset=['event'])
d = {k: v[['EST','event']].to_dict(orient='records') for k, v in df1.groupby('variable')}
print (d)
{'Monday': [{'EST': '7:00PM', 'event': 'Prayer'},
{'EST': '8:00PM', 'event': 'Board game'}],
'Tuesday': [{'EST': '12:00AM', 'event': 'Starting'},
{'EST': '8:00PM', 'event': 'Ask anything'}],
'Wednesday': [{'EST': '7:00PM', 'event': 'Game Night'}]}
Upvotes: 2