ben martin
ben martin

Reputation: 13

read the dictionary value from array

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

Is that a proper way to the value of the target item in Calories? Like getting 200, 140, such like that.

Trying to get the value of the calories. That is all.

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

Upvotes: 0

Views: 144

Answers (2)

Robᵩ
Robᵩ

Reputation: 168726

No, the proper way would be:

result.cal = CALORIES[name]

Upvotes: 1

aIKid
aIKid

Reputation: 28302

Just use dict.values, which returns all the values of the dictionary:

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

This will result:

>>> print result
[200, 140]

Full code:

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

Hope this helps!

Upvotes: 0

Related Questions