如何让python使用字典打印出正确的输出



所以我创建了一个列表和一个函数,该函数将一个单独的列表作为字典返回,如下所示所以第一个列表是这个

r = ["T-bone", "Green Salad1"]

将输出作为字典返回的函数是。。。

def rdict(recipes):
recipes_splitted = {}
for r in recipes:
recipe_name, parts = r.split(":")
recipe_parts = {}
for part in parts.split(','):
product, number = part.split('*')
recipe_parts[product] = int(number)
recipes_splitted[recipe_name] = recipe_parts
return recipes_splitted

上面函数的输出在字典中,类似于btw

{'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5}, 'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}

现在,我正试图创建一个函数extract(recipes, data),它将返回字典中提供的值和列表中提供的匹配键。返回类型应为列表。

例如,如果输入是

extract(recipes = ["T-bone", "Green Salad1"], data = {'Pork Stew': {'Cabbage': 5, 'Carrot': 1, 'Fatty Pork': 10}, 'Green Salad1': {'Cabbage': 10, 'Carrot': 2, 'Pineapple': 5}, 'T-Bone': {'Carrot': 2, 'Steak Meat': 1}}  )

输出将返回以下列表

["Carrot:2, Steak Meat:1","Cabbage: 10, Carrot: 2, Pineapple: 5"]

我应该在estact(配方、数据(下写些什么才能得到正确的输出??

尝试:

def extract(recipes, data):
result = []
for r in recipes:
result.append(", ".join(f"{k}:{v}" for k, v in data[r].items()))
return result

结果:

['Carrot:2, Steak Meat:1', 'Cabbage:10, Carrot:2, Pineapple:5']
  • 编辑

没有joinitemsdict理解:

def extract(recipes, data):
result = []
for r in recipes:
tmp = []
for key in data[r]:
tmp.append(f"{key}:{data[r][key]}")
final_string = ""
for i in range(len(tmp)):
if i < len(tmp) - 1:
final_string += tmp[i] + ", "
else:
final_string += tmp[i]
result.append(final_string)
return result

最新更新