我正在试图弄清楚如何使用用户输入的数据作为输入来从TinyDB DB获取信息。
我的数据库看起来像这样:
{"_default": {"1": {"switch": "n9k-c9372px", "names": ["nexus 9372px", "nexus 9372-px", "nexus9372px", "n9372px", "n9k-c9372px"], "fex_comp": ["2224tp", "2232pp"]}, "2": {"switch": "n9k-c9396px", "names": ["nexus 9396px", "nexus 9396-px", "nexus9396px", "n9396px", "n9k-c9396px"], "fex_comp": ["2232tm-e", "2248tp"]}}}
基本上,DB是带有列表的两个词典的结果,如下所示:
{"switch": "switch1", "names": ["name1", "name2", "name3"], "fex_comp":["fex1", "fex2", "fex3"]
我的想法如下:
我理解如何形成if,else语句以及如何使用for循环,但我还没弄清楚如何做我上面描述的内容。
非常感谢任何帮助!
爱德华
答案 0 :(得分:0)
那样的话呢?
from tinydb import TinyDB, Query
ql = ['nexus9372px','nexus9396px', 'not_there']
def mkdb():
db = TinyDB('db.json')
db.purge()
db.insert({'switch': 'n9k-c9372px',
'names': ['nexus 9372px',
'nexus 9372-px',
'nexus9372px', 'n9372px'],
'fex_comp': ['2224tp', '2232pp',
'2232tm', '2232tm-e']})
db.insert({"switch": "n9k-c9396px",
"names": ["nexus 9396px", "nexus 9396-px",
"nexus9396px", "n9396px",
"n9k-c9396px"],
"fex_comp": ["2232tm-e", "2248tp"]})
return(db)
def get_name():
return(input('Name? '))
def search(name, db):
Name = Query()
res = db.search(Name.names.any(name))
if res:
#print(res)
print('fex_comp for {}: {}'.format(name, res[0]['fex_comp']))
else:
print('{} not found'.format(name))
db = mkdb()
name = get_name()
search(name, db)