从数组中读取字典值

时间:2013-11-06 03:40:56

标签: python arrays dictionary

FOODS = {'Beef', 'Chicken'}

# The calories for each food item (a dictionary, where 
# key = food name (string) and value = calories (int)
CALORIES = \
    { 'Beef' : 200,     \
     'Chicken' : 140,   \
    }

class Food():
    __slots__ = (
        'name',         # string name
        'cal'           # Calories
    )

def mkFood( name ):
    result = Food()
    result.name = name
    result.cal = [calories for calories in CALORIES.values()]
    return result

这是卡路里目标物品价值的正确方法吗?就像得到200,140那样。

试图获得卡路里的价值。就是这样。

result.cal = calorie in dict(CALORIES[1])

2 个答案:

答案 0 :(得分:1)

不,正确的方法是:

result.cal = CALORIES[name]

答案 1 :(得分:0)

只需使用dict.values,它将返回字典的所有值:

result.cal = [calories for calories in CALORIES.values()]

这将导致:

>>> print result
[200, 140]

完整代码:

def mkFood( name ):
    """Create and return a newly initialized Food item"""
    result = Food()
    result.cal = [calories for calories in CALORIES.values()]
    return result

希望这有帮助!