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

2024-10-02 22:35:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果不使用类,我如何做到这一点?因此,如果有一个输入,例如“选择名称类型”,那么它应该返回“michielman” 简·曼


Tags: 字符串用户name名称信息列表字典属性
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:34

首先,您需要从查询中获取属性名称,然后就相当简单了

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
]

相关问题 更多 >