使用按日期分组将字典列表转换为字典列表

时间:2017-10-13 09:39:29

标签: python list dictionary itertools

我有下面的词典列表

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"
    }

]

我想转换为自定义词典列表&按日期分组。 样本输出

                "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"
                }

]

我尝试使用itertools groupby函数但未能获得预期的结果。

我使用的代码:

    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>)]

1 个答案:

答案 0 :(得分:2)

你的代码并没有那么远,但是你不必只是在列表理解中收集结果,而是必须使用混合列表和字典理解来创建dicts列表的内部序列。试试这个:

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)]

结果res

[{'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'}]}]