简体   繁体   English

带字典的Defaultdict

[英]Defaultdict with Dict

I have a dictionary like this 我有这样的字典

a = [{'CohortList': [{'DriverValue': 0.08559936}, {'DriverValue': 0.08184596527051588}], 
      '_id': {'DriverName': 'Yield', 'MonthsOnBooks': 50, 'SegmentName': 'LTV110-Super Prime'}},
     {'CohortList': [{'DriverValue': 2406.04329}, {'DriverValue': 2336.0058100690103}, ], 
      '_id': {'DriverName': 'ADB', 'MonthsOnBooks': 15, 'SegmentName': 'LTV110-Super Prime'}},
     {'CohortList': [{'DriverValue': 2406.04329}, {'DriverValue': 2336.0058100690103}, ], 
      '_id': {'DriverName': 'ADB', 'MonthsOnBooks': 16, 'SegmentName': 'LTV110-Prime'}}]

I want to construct a list of dictionary with values as lists from the above dict set like this 我想构造一个字典列表,其值是上述字典集合中的列表

    {
    "LTV110-Prime": [
        {
            "ADB": [
                {
                    "16": 1500
                }
            ]
        },
        {
            "Yield": []
        }
    ],
    "LTV110-Super Prime": [
        {
            "ADB": [
                {
                    "15": 1500
                }
            ]
        },
        {
            "Yield": [
                {
                    "50": 0.09
                }
            ]
        }
    ]
}

Essentially, I want to group ADB and Yield for each segments with their values. 本质上,我想将每个细分的ADB和Yield与其值分组。

This is what I have done so far to achieve this target. 到目前为止,这是我为实现该目标所做的工作。 The values for ADB are mean of DriverValue from CohortList list. ADB的值是CohortList列表中DriverValue的平均值。 I have used statistics.mean to find out the mean of the mapped values. 我使用statistics.mean来找出映射值的平均值。

sg_wrap = defaultdict(dict)
for p in pp_data:
    mapped = map(lambda d: d.get('DriverValue', 0), p['CohortList'])
    dic = {p['_id']['MonthsOnBooks']: statistics.mean(mapped)}

    print(p)
print(sg_wrap)

I am not able to append the Drivers to the inner dict. 我无法将驱动程序附加到内部字典。 Please help. 请帮忙。

Since you are wrapping everything into lists, you do not need a defaultdict(dcit) but a defaultdict(list) . 由于将所有内容包装到列表中,因此不需要defaultdict(dcit)而是defaultdict(list)

The following seems to work: 以下似乎有效:

result = defaultdict(list)
for entry in a:
    id_ = entry["_id"]
    name, months, segment = id_["DriverName"], id_["MonthsOnBooks"], id_["SegmentName"]
    values = [x["DriverValue"] for x in entry["CohortList"]]
    d = {name: [{months: statistics.mean(values)}]}
    result[segment].append(d)

Result is 结果是

{'LTV110-Prime': [{'ADB': [{16: 2371.0245500345054}]}],
 'LTV110-Super Prime': [{'Yield': [{50: 0.08372266263525793}]},
                        {'ADB': [{15: 2371.0245500345054}]}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM