在Python中访问字典列表的键和值

时间:2017-09-02 20:01:19

标签: python list dictionary

我在Python中使用一个列表来存储字典,其中包含配方成分作为键,每个成分的数量作为每个字典的值。例如;

Ingredients = [{'Pizza Base' : 'Medium Size'}, {'Cheese' : '200g'}, {'Sauce' : '200g'}]

如何访问每种成分和金额?

我知道如何访问列表中的每个字典,但我不知道如何访问每个字典中的值。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案:

Ingredients = [{'Pizza Base' : 'Medium Size'}, {'Cheese' : '200g'}, {'Sauce' : '200g'}]
for ing in Ingredients:
  name = list(ing.keys())[0]
  amount = ing[name]
  print(name,':',amount)

以上输出:

Pizza Base : Medium Size
Cheese : 200g
Sauce : 200g