繁体   English   中英

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

[英]How do I format dictionary Key and Values using format()

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

这是食谱(“寿司”,“金枪鱼”,“米饭”,“蛋黄酱”,“芥末”)

  1. 洗净金枪鱼

但是我想要这个:

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

  1. 洗净金枪鱼

我可以使用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"

您可以使用join()来连接字典的值,例如以下示例:

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"

由于您是从随机检索元组,因此请找到以下工作代码

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"

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

在下面的代码中用您的recipe_dict替换a

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM