Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从数组中读取字典值_Python_Arrays_Dictionary - Fatal编程技术网

Python 从数组中读取字典值

Python 从数组中读取字典值,python,arrays,dictionary,Python,Arrays,Dictionary,这是一个正确的方法,以卡路里的目标项目的价值?比如200,140,像这样 试图得到卡路里的价值。仅此而已 result.cal=dict中的卡路里(卡路里[1])只需使用dict.values,它返回字典中的所有值: FOODS = {'Beef', 'Chicken'} # The calories for each food item (a dictionary, where # key = food name (string) and value = calories (int) CA

这是一个正确的方法,以卡路里的目标项目的价值?比如200,140,像这样

试图得到卡路里的价值。仅此而已


result.cal=dict中的卡路里(卡路里[1])

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

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
这将导致:

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

您的词典缺少一个结束语
}
。此外,如果您放置开头
{
carries=
Oops在同一行。我的教授想让我把``放在那里。一个建议传下去。你可以运行python作为一个解释器,玩一下命令会做什么。只需启动'python'或'python.exe'并在其中键入python语言代码。然后你就可以看到'foo in dict'或'[x代表foo.values()]中的x即可。
result.cal = CALORIES[name]