[英]How do I format dictionary Key and Values using format()
使用Python 2.7的Python新手。 我正在創建一個程序,打印出帶有其成分和說明的隨機配方。 我將在最后發布我的代碼。 我得到的輸出是:
這是食譜(“壽司”,“金槍魚”,“米飯”,“蛋黃醬”,“芥末”)
- 洗凈金槍魚
但是我想要這個:
這是食譜:壽司:金槍魚,大米,蛋黃醬,芥末
- 洗凈金槍魚
我可以使用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.