读取属性名称并从字典返回属性信息



我正在尝试编写一个简单的查询,它将返回所有请求的属性。这个想法是读取属性名称并返回属性信息。它应该以字符串"select"开头,然后是用户想要看到的属性列表

因此,有一个由字典组成的小型数据库:

dsql_table = 
[{'name': 'Jan', 'type': 'man', 'profession': 'Analyst'},
{'name': 'Max', 'type': 'man', 'profession': 'Doctor'}] 

这个想法是只实现功能(忽略错误处理(:

try:
query = input('dsql> ')
while query != 'exit':
# I need to implement code over here
print ('Thank you!') 

如何在不使用类的情况下执行此操作?因此,如果一个输入,例如"选择名称类型",那么它应该返回"michiel man 扬曼'。

首先,您需要从查询中获取属性名称,然后非常简单。

dsql_table = [
{'name': 'Jan', 'type': 'man', 'profession': 'Analyst'},
{'name': 'Max', 'type': 'man', 'profession': 'Doctor'},
]
query = 'select name type'
# extract selected attributes from query
selected_attributes = query.split()[1:]
result = []
for record in dsql_table:
# iterate over selected attributes, store value if attribute exists
for attribute in selected_attributes:
if attribute in record:
result.append(record[attribute])
# now result is a list ['Jan', 'man', 'Max', 'man']
print(' '.join(result))

或者,可以使用列表推导式填充result

result = [
record[attribute]
for record in dsql_table
for attribute in selected_attributes
if attribute in record
]

最新更新