all_brands_scores = dict(sorted(all_brands_scores.items(), key=lambda item: item[1]))
print(all_brands_scores )
output:
{'ADATA': 0, 'GIGABYTE': 0, 'CyberPowerPC': 0, 'Hyundai': 0, 'Thomson': 0, 'KANO': 1, 'Alienware': 1, 'Razer': 1, 'Google': 1, 'LG': 2, 'HP OMEN': 5, 'Acer': 12, 'Apple': 13, 'Microsoft': 13, 'MSI': 17, 'Samsung': 18, 'Dell': 24, 'ASUS': 54, 'Lenovo': 71, 'HP': 104}
I have this file(dic) but not as fixed values How do I calculate the percentage of each type of laptop ?
CodePudding user response:
If you want to replace the original values with their percentages:
total = sum(all_brands_scores.values())
for key,val in all_brands_scores.items():
all_brands_scores[key] = round(val/total * 100, 2)
If you want a new dictionary of percentages:
perc_dict = {}
total = sum(all_brands_scores.values())
for key,val in all_brands_scores.items():
perc_dict[key] = round(val/total * 100, 2)
If you want to add the % symbol, then you will have to convert the values into string format:
perc_dict = {}
total = sum(all_brands_scores.values())
for key,val in all_brands_scores.items():
perc_dict[key] = str(round(val/total * 100, 2)) '%'
(Rounding off the percentages till 2 decimal places.)
CodePudding user response:
sum_of_values = sum(data.values())
dict(
map(
lambda v:
[
v[0],
str(v[1] / sum_of_values * 100) "%"
],
data.items()
)
)