Kush Vyas
Kush Vyas

Reputation: 6079

Convert a list of dictionary into list of dictionary by using group by date

I have below a list of dictionaries

Data = [{"Date": "Fri, 13 Oct 2017 00:00:00 GMT",
         "In_Time": "Fri, 13 Oct 2017 13:10:00 GMT",
         "Owner_Name": "Ashish Bainade"},
        {"Date": "Fri, 13 Oct 2017 00:00:00 GMT",
         "In_Time": "Fri, 13 Oct 2017 13:03:00 GMT",
         "Owner_Name": "Akshara Bainade"},
        {"Date": "Fri, 12 Oct 2017 00:00:00 GMT",
         "In_Time": "Fri, 12 Oct 2017 13:03:00 GMT",
         "Owner_Name": "Sam"}]

I want to convert into a custom list of dictionaries & with group by date. Sample output is:

"Data": [{"Visitors": [{"In_Time": "Fri, 13 Oct 2017 13:10:00 GMT",
                        "Owner_Name": "Ashish Bainade"},
                       {"In_Time": "Fri, 13 Oct 2017 13:03:00 GMT",
                        "Owner_Name": "Akshara Bainade"}],
          "Date": "Fri, 13 Oct 2017 00:00:00 GMT"},
         {"Visitors": [{"In_Time": "Fri, 12 Oct 2017 13:10:00 GMT",
                        "Owner_Name": "sam"}],
          "Date": "Fri, 13 Oct 2017 00:00:00 GMT"}]

I tried using itertools.groupby function but failing to get the expected result.

The code which I used :

from itertools import groupby

group_by_field = 'Date'
f = lambda x: x[group_by_field]
response = [item for item in groupby(sorted(Data, key=f), f)]
print response
# [('Fri, 12 Oct 2017 00:00:00 GMT', <itertools._grouper object at 0x000000000288E2B0>), ('Fri, 13 Oct 2017 00:00:00 GMT', <itertools._grouper object at 0x000000000288E1D0>)]

Upvotes: 1

Views: 220

Answers (1)

tobias_k
tobias_k

Reputation: 82899

Your code is not that far off the mark, but instead of just collecting the results in a list comprehension, you have to use a mixed list- and dictionary comprehension to create the inner dicts of lists of dicts. Try this:

f = lambda x: x['Date']
res = [{"Date": key, "Visitors": [{k: d[k] for k in d if k != "Date"} for d in group]}
       for key, group in itertools.groupby(sorted(Data, key=f), f)]

The result res is then

[{'Date': 'Fri, 12 Oct 2017 00:00:00 GMT',
  'Visitors': [{'In_Time': 'Fri, 12 Oct 2017 13:03:00 GMT',
                'Owner_Name': 'Sam'}]},
 {'Date': 'Fri, 13 Oct 2017 00:00:00 GMT',
  'Visitors': [{'In_Time': 'Fri, 13 Oct 2017 13:10:00 GMT',
                'Owner_Name': 'Ashish Bainade'},
               {'In_Time': 'Fri, 13 Oct 2017 13:03:00 GMT',
                'Owner_Name': 'Akshara Bainade'}]}]

Upvotes: 2

Related Questions