首页 > 解决方案 > python nutrition log. Assigning multiple values to each key

问题描述

I'm building a nutrition log. I've started with assigning caloric values to food items

IE: {'granola': 160, 'yogurt': 110, 'coffee': 5}

What I would like to is have food items and list fat, carb and protein and sodium levels per food item in grams:

IE: 'granola': fat: 6g, carbs: 32g, protein: 6,

'yogurt': fat: 8g, carbs: 2g, protein: 12

What is the best way to assign multiple values per dictionary key?

标签: pythonpython-3.xlist

解决方案


下面的代码会帮助你。

s = {}
s['granola'] = {}
s['granola']['fat'] = 6

print(s)

s['granola']['crabs'] = 32
s['granola']['protein'] = 6

print(s)

print(s['granola']['crabs'])

s['granola']['vitamin'] = {}
s['granola']['vitamin']['a'] = 6
s['granola']['vitamin']['b'] = 60

print(s['granola']['vitamin']['b'])
print(s)

# To edit the values

s2 = {'granola': {'fat': 6, 'crabs': 32, 'protein': 6}, 'choc_milk': {'calories': 140, 'fat': 5, 'carbs': 13, 'protein': 13}}

for i in s2:
    for j in s2[i]:
        s2[i][j] *= 1.5
        
print(s2)

上述代码的输出

{'granola': {'fat': 6}}
{'granola': {'fat': 6, 'crabs': 32, 'protein': 6}}
32
60
{'granola': {'fat': 6, 'crabs': 32, 'protein': 6, 'vitamin': {'a': 6, 'b': 60}}}
{'granola': {'fat': 9.0, 'crabs': 48.0, 'protein': 9.0}, 'choc_milk': {'calories': 210.0, 'fat': 7.5, 'carbs': 19.5, 'protein': 19.5}}
> 

推荐阅读