I have a list with multiple dict() inside of it.
Here is my 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}]
My end goal is to make a single dict with an average from the above dicts.
Example:
[{'clicks': 1.2048192771084338, 'conversions': 1.4056224899598393, 'cpc': 2.208835341365462, 'cpm': 5.622489959839357, 'reach': 89.5582329317269}]
My problem is how do I access and compare the keys from multiple dict at a time?
Is there a better way to do it?
Thanks. I am very new to programming
CodePudding user response:
Try this...
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)
Or you can also try this One-line code
print({j:sum([i[j] for i in lst])/len([i[j] for i in lst]) for j in lst[0].keys()})
Tell me if its not working...
CodePudding user response:
If all dictionaries in the list have the same keys, you can use:
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)
Prints:
{
"clicks": 1.2121657361151925,
"conversions": 1.4141933588010578,
"cpc": 2.2223038495445193,
"cpm": 5.047017337643256,
"reach": 90.10431971789598,
}
CodePudding user response:
I hope the following code will help you to get understand how to find the average values of multiple lists of dict items
# 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)
output
{'clicks': 1.2121657361151925,
'conversions': 1.4141933588010578,
'cpc': 2.2223038495445193,
'cpm': 5.047017337643256,
'reach': 90.10431971789598}