从字典中读取属性名称和 return 属性信息

Read attribute names and return attribute information from dictionary

我正在尝试编写一个简单的查询,它将 return 请求的所有属性。这个想法是读取属性名称和 return 属性信息。它应该以字符串 '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!') 

如何在不使用 类 的情况下执行此操作?因此,如果一个输入,例如'select name type',那么应该是 return '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
]