如何返回所有字典的键,并在Python 3.4中将它们打印出来?

时间:2022-03-22 07:37:54

Here is a section of my Python 3.4 code. It does exactly what I want it to but I would like to have the variable "ingredients" and the keys from my dictionary "lemon_drizzle" to Return so that i can use them outside of the function.

这是我的Python 3.4代码的一部分。它完全符合我的要求,但我希望将变量“ingredients”和我的字典“lemon_drizzle”中的键设置为Return,以便我可以在函数之外使用它们。

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)

Thank you for listening to, and hopefully answering my question! P.S this is prob a really simple problem!

感谢您的倾听,希望能回答我的问题! P.S这是一个非常简单的问题!

1 个解决方案

#1


This is an indentation problem. Try this:

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

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)

I also replaced your multiline string literal (the one with triple quotes) by Python comments. If you really want the multiline string, be careful to indent it correctly.

我还用Python注释替换了你的多行字符串文字(带三引号的文字)。如果你真的想要多线字符串,请小心缩进它。

Also

plain_flour2 = lemon_drizzle['Plain Flour']= 120

can probably be replaced with:

可以替换为:

lemon_drizzle['Plain Flour']= 120

#1


This is an indentation problem. Try this:

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

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)

I also replaced your multiline string literal (the one with triple quotes) by Python comments. If you really want the multiline string, be careful to indent it correctly.

我还用Python注释替换了你的多行字符串文字(带三引号的文字)。如果你真的想要多线字符串,请小心缩进它。

Also

plain_flour2 = lemon_drizzle['Plain Flour']= 120

can probably be replaced with:

可以替换为:

lemon_drizzle['Plain Flour']= 120