【问题标题】:How do I return all of a dictionary's keys, and print them out side of the function in Python 3.4?如何返回字典的所有键,并在 Python 3.4 中将它们打印到函数之外?
【发布时间】:2015-07-13 01:38:41
【问题描述】:

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

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)

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

【问题讨论】:

    标签: function python-3.x dictionary return


    【解决方案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)
    

    我还用 Python cmets 替换了您的多行字符串文字(带有三引号的文字)。如果您真的想要多行字符串,请注意正确缩进。

    还有

    plain_flour2 = lemon_drizzle['Plain Flour']= 120
    

    可以替换为:

    lemon_drizzle['Plain Flour']= 120
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多