【问题标题】:Python: How to store multiple values for one dictionary keyPython:如何为一个字典键存储多个值
【发布时间】:2015-03-06 10:54:35
【问题描述】:

我想将成分列表存储在字典中,使用成分名称作为键并将成分数量和测量值存储为值。例如,我希望能够做这样的事情:

ingredientList = {'flour' 500 grams, 'tomato' 10, 'mozzarella' 250 grams}

使用“番茄”键,番茄没有尺寸,只有数量。我可以在 Python 中实现这一点吗?是否有替代或更有效的方法来解决这个问题?

【问题讨论】:

  • 输入是什么?你的代码在哪里?

标签: python list dictionary key key-value


【解决方案1】:

如果您想要列表,请使用列表:

ingredientList = {'flour': [500,"grams"], 'tomato':[10], 'mozzarella' :[250, "grams"]}

获取物品:

weight ,meas = ingredientList['flour']
print(weight,meas)
(500, 'grams')

如果你只想更新ingredientList[key].append(item)

【讨论】:

    【解决方案2】:

    你可以使用另一个字典。

    ingredientList = {
        'flour': {'quantity': 500, 'measurement': 'grams'},
        'tomato': {'quantity': 10},
        'mozzarella': {'quantity': 250, 'measurement': 'grams'}
    }
    

    然后你可以像这样访问它们:

    print ingredientList['mozzarella']['quantity']
    >>> 250
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-28
      • 2018-08-14
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      相关资源
      最近更新 更多