python - 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?
解决方案
下面的代码会帮助你。
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}}
>
推荐阅读
- godot - 有没有办法保存场景并排除 Godot 中的某些资产?
- android-studio - Kotlin,Android,如何正确调试协程?
- java - 结果设置为表格模型
- java - HashMap 值没有改变
- java - 基于 HTTP 查询从 JSON 响应获取图像时出错
- java - 在 Java Wireless Toolkit 中运行应用程序的困难
- symfony - 简单的管理包。Trix 编辑器。更改代码段的包装标签。
->
- python-3.x - Trying to webscrape amazon.in using BeautifulSoup
- javascript - Chartjs - Laravel 5.8 未定义未捕获的参考错误图表
- java - Java中的多重继承。通过扩展顺序分配优先级