首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何返回字典的所有键,并在Python3.4的函数中打印出来?

如何返回字典的所有键,并在Python3.4的函数中打印出来?
EN

Stack Overflow用户
提问于 2015-05-04 01:32:51
回答 1查看 32关注 0票数 0

下面是我的Python3.4代码的一部分。它完全符合我的要求,但我希望返回变量“配料”和字典中的键"lemon_drizzle“,这样我就可以在函数外部使用它们。

代码语言:javascript
复制
how_lemon= int(input('How many lemon drizzle cakes would you like to
bake?'))

#list of the ingredients for cakes
lemon_drizzle={
     'Double Cream':140,
     'Lemon Zest':3,
     'Salt':1,
     'Baking Power':0.5}
plain_flour2 = lemon_drizzle['Plain Flour']= 120
sugar2 = lemon_drizzle['Sugar']= 140
unsalted_butter2 = lemon_drizzle['Unsalted Butter']= 40
free_eggs2 = lemon_drizzle['Free Range Eggs']= 1


def function_ingredients(cake, how_many):
   for key,val in cake.items():
    ingredients = val * how_many

    '''
    I want this to return 'ingredients' and all the keys
    so that it does exactly the same this, but outside the function.
    '''

    print(ingredients, key)



print('\nFor your lemon drizzle cakes you will need:\n')    
lemon_ingredients = function_ingredients(lemon_drizzle, how_lemon)

感谢您的收听,希望您能回答我的问题!附言:这是一个非常简单的问题!

EN

回答 1

Stack Overflow用户

发布于 2015-05-04 04:24:07

这是一个缩进问题。试试这个:

代码语言:javascript
复制
def function_ingredients(cake, how_many):
    for key,val in cake.items():
        ingredients = val * how_many  
#    I want this to return 'ingredients' and all the keys
#    so that it does exactly the same this, but outside the function.
        print(ingredients, key)

我还用Python注释替换了您的多行字符串文字(带有三重引号的字符串)。如果您确实需要多行字符串,请小心正确地缩进它。

也是

代码语言:javascript
复制
plain_flour2 = lemon_drizzle['Plain Flour']= 120

可以替换为:

代码语言:javascript
复制
lemon_drizzle['Plain Flour']= 120
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30017081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档