如何在Python字典中搜索?
我有一本包含食谱的Python词典。我必须找到其中的键值,然后根据这些键值的位置返回结果如何在Python字典中搜索?,python,Python,我有一本包含食谱的Python词典。我必须找到其中的键值,然后根据这些键值的位置返回结果 recipes = { 'recipe1':{ 'name': 'NAME', 'components': { '1':{ 'name1':'NAME', 'percent':'4 %' }, '2':{
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']
}
}
每个配方都有一个
关键字列表
。如何根据配方的关键字和一些搜索输入查找配方?在找到配方后,我需要返回该配方特定的名称组件和时间。如果在名为search
的变量中输入了一些内容,您可以执行以下操作:
for v in recipes.values():
if search in v['keywords']:
# Found the recipe of interest.
return v['components'], v['time']
不幸的是,您当前存储数据的方式阻止您利用字典中的O(1)
查找时间。(如果在配方
字典中有多个配方,这可能会影响性能。)因此,除非重构数据结构,否则必须迭代配方
中的键值对才能找到配方。在名为搜索
的变量中输入一些内容,可以执行以下操作:
for v in recipes.values():
if search in v['keywords']:
# Found the recipe of interest.
return v['components'], v['time']
不幸的是,您当前存储数据的方式阻止您利用字典中的O(1)
查找时间。(如果在配方
字典中有多个配方,这可能会影响性能。)因此,除非重构数据结构,否则必须迭代配方
中的键值对才能找到配方。请执行以下操作
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 days
你喜欢下面吗
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 days
为什么关键字
嵌套在recipe1
中?这不是应该提高一个水平吗?甚至可能在字典之外?而关键字是否应该像dict
的键一样?@pushkin不,每个配方都有自己的关键字集,就像每个配方都有自己的名字一样。@chepner哦,duh。我忘记了关键字这个词在编程上下文之外的含义。谢谢我相信你的问题在这里有答案:为什么关键字嵌套在recipe1
中?这不是应该提高一个水平吗?甚至可能在字典之外?而关键字是否应该像dict
的键一样?@pushkin不,每个配方都有自己的关键字集,就像每个配方都有自己的名字一样。@chepner哦,duh。我忘记了关键字这个词在编程上下文之外的含义。谢谢我相信你的问题在这里有答案: