I have a 3d list, of strings and numbers. I need to calculate the sum of each color. Plus, what percentage each item contributes to that total color.
This is what I currently have.
from collections import defaultdict
d = defaultdict(int)
dc = defaultdict(int)
l = [('red', 'apple', 7), ('red', 'car', 4), ('red', 'shoe', 3), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]
for color, name, number in l:
d[color] = number
total = str(d)
for color, name, number in l:
dc[color] /= number
percent = str(dc)
print(total, percent)
What it's printing though is this:
defaultdict(<class 'int'>, {'red': 14, 'blue': 9, 'green': 2}) defaultdict(<class 'int'>, {'red': 0.0, 'blue': 0.0, 'green': 0.0})
The expected output is:
red: 14
blue: 9
green: 2
red apple: 7/14 = 50%
red car: 4/14 = 29%
red shoe: 3/14 = 21%
blue candy: 4/9 = 44%
blue bike: 5/9 = 56%`
CodePudding user response:
You need to iterate one more times on dc
and use value of d
base color_key
.
from collections import defaultdict
d = defaultdict(int)
dc = defaultdict(int)
l = [('red', 'apple', 0), ('red', 'car', 0), ('red', 'shoe', 0), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]
for color, name, val in l:
d[color] = val
dc[(color, name)] = val
print(d)
dc = {f"{color} {name}" : round(val / d[color], 2) if d[color]!=0 else 'division by zero'
for (color, name), val in dc.items()}
print(dc)
Output:
# print(d)
defaultdict(<class 'int'>, {'red': 14, 'blue': 9, 'green': 2})
# print(dc)
{'red apple': 0.5, 'red car': 0.29, 'red shoe': 0.21, 'blue candy': 0.44, 'blue bike': 0.56, 'green melon': 1.0}