如何使用format()格式化字典键和值

时间:2017-06-17 05:20:59

标签: python python-2.7

Python新手,使用Python 2.7。我正在创建一个程序,打印出随机配方及其成分和说明。我会在最后发布我的代码。我得到的输出是:

  

这是一个食谱('寿司',''金枪鱼','米饭','蛋黄酱','芥末')

     
      
  1. 洗掉金枪鱼
  2.   

但我想要这个:

  

这是一个食谱:寿司:金枪鱼,米饭,蛋黄酱,芥末

     
      
  1. 洗掉金枪鱼
  2.   

我可以使用format()方法来完成这样的事情吗?

这是我的代码:

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"

3 个答案:

答案 0 :(得分:3)

您可以使用join()加入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"

答案 1 :(得分: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"

您将使用此代码获得预期的输出。

答案 2 :(得分:0)

使用以下代码中的a替换recipe_dict

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