2017-06-17 44 views
1

Python新手這裏,使用Python 2.7格式字典鍵和值。我正在創建一個程序,用它的原料和說明打印出一份隨機配方。我會在最後發佈我的代碼。我得到的輸出是:如何使用格式()

這裏是一個配方( '壽司',[ '金槍魚', '飯', '蛋黃醬', '綠芥末'])

  1. 洗掉金槍魚

但我想這一點:

這裏是一個食譜:壽司:金槍魚,大米,蛋黃醬,芥末

  1. 洗掉金槍魚

我可以使用格式()方法來完成這樣的事情?

這裏是我的代碼:

import random 

def random_recipe(): 
    recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
        'Pasta':['noodles', 'marinara','onions'], 
        'Sushi':['tuna','rice','mayonnaise','wasabi']} 


    print "Here is a recipe" + str(random.choice(list(recipe_dict.items()))) 

    if recipe_dict.keys() == 'ChocolateCake': 
     print "1. Mix the flour with the eggs" 
    elif recipe_dict.keys() == 'Pasta': 
     print "1. Boil some water" 
    else: 
     print "1. Wash off the tuna" 
+0

一些需要注意的是,這將始終打印' 1。因爲'recipe_dict.keys()== ['Pasta','Sushi','ChocolateCake']'無論食譜如何,都可以洗掉金槍魚,永遠不會是elif中的任何一種。 – timotree

+0

謝謝@timotree – johnnewbie25

回答

1

因爲你是從隨機檢索元組,查找下面的工作代碼

import random 

recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
       'Pasta':['noodles', 'marinara','onions'], 
       'Sushi':['tuna','rice','mayonnaise','wasabi']} 


ra_item = random.choice(list(recipe_dict.items())) 
print "Here is a recipe {}:{}".format(ra_item[0],','.join(ra_item[1])) 

if recipe_dict.keys() == 'ChocolateCake': 
    print "1. Mix the flour with the eggs" 
elif recipe_dict.keys() == 'Pasta': 
    print "1. Boil some water" 
else: 
    print "1. Wash off the tuna" 

你會得到這個代碼預期輸出。

+0

謝謝。 'join'方法在Python中做什麼? – johnnewbie25

+0

它實際上是一個字符串函數。它將採用迭代器(您的案例中的列表)中的值並加入您在引號內提到的字符。如果您接受答案,請給予贊成:) – Arockia

3

您可以使用join()加入你的字典的價值觀這樣的例子:在下面的代碼你recipe_dict

from random import choice 

recipe_dict = {'ChocolateCake':['flour', 'eggs', 'chocolate', 'oil', 'frosting'], 
        'Pasta':['noodles', 'marinara','onions'], 
        'Sushi':['tuna','rice','mayonnaise','wasabi']} 

# Or you can unpack your data: 
# key, val = choice(recipe_dict.items()) 
keys = list(recipe_dict.keys()) 
random_key = choice(keys) 
# Using str.format() 
print "Here is a recipe: {}: {}".format(random_key, ', '.join(recipe_dict[random_key])) 

if random_key == 'ChocolateCake': 
    print "1. Mix the flour with the eggs" 
elif random_key == 'Pasta': 
    print "1. Boil some water" 
else: 
    print "1. Wash off the tuna" 
0

替補a

for k, v in a.items(): 
    print(k + ': ' + ','.join(map(str, v)))