我有一本包含食谱的Python字典。我必须在其中找到键值,然后根据这些键的位置返回结果。
recipes = {
'recipe1':{
'name': 'NAME',
'components': {
'1':{
'name1':'NAME',
'percent':'4 %'
},
'2':{
'name2':'NAME',
'percent':'3 %'
},
'3':{
'name3':'NAME',
'percent':'1 %'
},
},
'time':'3-5 days',
'keywords':['recipe1', '1','etc']
}
}每个食谱都有一个keywords列表。如何根据食谱的keywords和一些搜索输入来查找食谱?找到食谱后,我需要返回特定于该食谱的名称、组件和时间。
发布于 2018-03-15 03:06:21
在名为search的变量中给定一些输入,您可以执行以下操作:
for v in recipes.values():
if search in v['keywords']:
# Found the recipe of interest.
return v['components'], v['time']不幸的是,您当前存储数据的方式使您无法利用字典中的O(1)查找时间。(如果recipes字典中有多个配方,这可能会影响性能。)因此,除非重构数据结构,否则必须遍历recipes中的键-值对才能找到方法。
发布于 2018-03-15 03:38:06
如下图所示
list = ['etc', 'cc', 'ddd']
for x, y in recipes.items():
for m in y['keywords']:
if m in list:
print('Name : ' + y['name'])
print('Components : ')
for i in y['components'].keys():
print(str(i), end=' ')
for j in y['components'][i]:
print(j + " " + y['components'][i][j], end=' ')
print('')
print('\nTime: ' + str(y['time']))输出:
Name : NAME
Components :
1 name1 NAME percent 4 %
2 name2 NAME percent 3 %
3 name3 NAME percent 1 %
Time: 3-5 dayshttps://stackoverflow.com/questions/49285793
复制相似问题