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

时间:2020-06-11 09:21:57

标签: python dictionary attributes

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

1 个答案:

答案 0 :(得分:0)

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

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
]
相关问题