比较列表中多个字典的键和值

Compare keys and values from multiple dicts inside a list

我有一个包含多个词典的列表。

这是我的清单:

[{'clicks': 1.2195121951219512, 'conversions': 1.4227642276422763, 'cpc': 2.2357723577235773, 'cpm': 4.471544715447155, 'reach': 90.65040650406505}, 
{'clicks': 1.2048192771084338, 'conversions': 1.4056224899598393, 'cpc': 2.208835341365462, 'cpm': 5.622489959839357, 'reach': 89.5582329317269}]

我的最终目标是制作一个 dict 具有上述指令的平均值。

示例:

[{'clicks': 1.2048192771084338, 'conversions': 1.4056224899598393, 'cpc': 2.208835341365462, 'cpm': 5.622489959839357, 'reach': 89.5582329317269}]

我的问题是:如何一次访问和比较来自多个字典的键?有更好的方法吗?

试试这个...

lst = [{'clicks': 1.2195121951219512, 'conversions': 1.4227642276422763, 'cpc': 2.2357723577235773, 'cpm': 4.471544715447155, 'reach': 90.65040650406505},
       {'clicks': 1.2048192771084338, 'conversions': 1.4056224899598393, 'cpc': 2.208835341365462, 'cpm': 5.622489959839357, 'reach': 89.5582329317269}]

res = {}
keys_ = ['clicks', 'conversions', 'cpc', 'cpm', 'reach']
for j in keys_:
    temp = [i[j] for i in lst]
    res[j] = sum(temp)/len(temp)

print(res)

或者你也可以试试这个单行代码

print({j:sum([i[j] for i in lst])/len([i[j] for i in lst]) for j in lst[0].keys()})

如果它不起作用请告诉我...

如果列表中的所有词典都有相同的键,您可以使用:

from statistics import mean

lst = [
    {
        "clicks": 1.2195121951219512,
        "conversions": 1.4227642276422763,
        "cpc": 2.2357723577235773,
        "cpm": 4.471544715447155,
        "reach": 90.65040650406505,
    },
    {
        "clicks": 1.2048192771084338,
        "conversions": 1.4056224899598393,
        "cpc": 2.208835341365462,
        "cpm": 5.622489959839357,
        "reach": 89.5582329317269,
    },
]

out = {k: mean(d[k] for d in lst) for k in lst[0]}
print(out)

打印:

{
    "clicks": 1.2121657361151925,
    "conversions": 1.4141933588010578,
    "cpc": 2.2223038495445193,
    "cpm": 5.047017337643256,
    "reach": 90.10431971789598,
}

我希望下面的代码能帮助您了解如何找到多个字典项列表的平均值

# your list of dict items
dlist = [{'clicks': 1.2195121951219512, 'conversions': 1.4227642276422763, 'cpc': 2.2357723577235773, 'cpm': 4.471544715447155, 'reach': 90.65040650406505}, 
{'clicks': 1.2048192771084338, 'conversions': 1.4056224899598393, 'cpc': 2.208835341365462, 'cpm': 5.622489959839357, 'reach': 89.5582329317269}]
newdict = {}
for d in dlist:
    for k, v in d.items():
        if k in newdict:
            newdict[k].append(v)
        else:
            newdict[k] = [v]
            
# find average from the new dict
for key, value in newdict.items():
    newdict[key] = sum(value)/len(value)
print(newdict)

输出

{'clicks': 1.2121657361151925,
 'conversions': 1.4141933588010578,
 'cpc': 2.2223038495445193,
 'cpm': 5.047017337643256,
 'reach': 90.10431971789598}