Home > Net >  combine and append dataframe as list of dictionarys to a response object
combine and append dataframe as list of dictionarys to a response object

Time:02-26

I have a dataframe in below format:

daily_dates registered attended
02/10/2022 0 0
02/09/2022 0 0
02/08/2022 1 0

And my response object is of this format:

response = {"registered":[], "attended":[]}

I am looking to combine daily_dates with registered and attended column to result in below response object.

response = {"registered":[{"02/10/2022":0},{"02/09/2022":0},{"02/08/2022":1}], "attended":[{"02/10/2022":0},{"02/09/2022":0},{"02/08/2022":0}]}

The below is my current coding approach:

weekly['registered'] = weekly.apply(lambda row: {row['daily_dates']: row['registered']}, axis=1)
response["registered"]  = weekly['registered'].tolist()

I am looking for a much efficient and direct way of achieving this.

CodePudding user response:

Direct but ugly:

response = {"registered":[], "attended":[]}
for _, d, r, a in weekly.itertuples(name=None):
    response['registered'].append({d: r})
    response['attended'].append({d: a})

CodePudding user response:

I think you can build it manually like this:

Option 1:

dd = df.set_index('daily_dates').to_dict()
for k in dd.keys():
  l = []
  for ki, v in dd[k].items():
      l.append({ki: v})
  dd[k] = l
dd

Output:

{'registered': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 1}],
 'attended': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 0}]}

Option 2 using defaultdict:

from collections import defaultdict
defd = defaultdict(list)

dd = df.set_index('daily_dates').to_dict()
[defd[k].append({ek:ev}) for k, v in dd.items() for ek, ev in v.items()]
dict(defd)

Output:

{'registered': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 1}],
 'attended': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 0}]}
  • Related