[英]How do I format dictionary Key and Values using format()
Python newbie here, using Python 2.7. 使用Python 2.7的Python新手。 I'm creating a program that prints out a random recipe with its ingredients and instructions.
我正在创建一个程序,打印出带有其成分和说明的随机配方。 I'll post my code at the end.
我将在最后发布我的代码。 The output I'm getting is:
我得到的输出是:
Here is a recipe('Sushi', ['tuna', 'rice', 'mayonnaise', 'wasabi'])
这是食谱(“寿司”,“金枪鱼”,“米饭”,“蛋黄酱”,“芥末”)
- Wash off the tuna
洗净金枪鱼
But I want this: 但是我想要这个:
Here is a recipe: Sushi: tuna, rice, mayonnaise, wasabi
这是食谱:寿司:金枪鱼,大米,蛋黄酱,芥末
- Wash off the tuna
洗净金枪鱼
Can I use the format() method to accomplish something like this? 我可以使用format()方法完成类似的事情吗?
Here is my code: 这是我的代码:
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"
You can use join()
to join your dict's values like this example: 您可以使用
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"
Since you are retrieving tuple from random, Find the below working code 由于您是从随机检索元组,因此请找到以下工作代码
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"
You will get the expected output with this code. 使用此代码,您将获得预期的输出。
Substitute a
with your recipe_dict
in the code below: 在下面的代码中用您的
recipe_dict
替换a
:
for k, v in a.items():
print( k + ': ' + ','.join(map(str, v)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.