首页 > 解决方案 > Python steamlit 选择框菜单返回字符串,但我需要 dict 或 list

问题描述

在这种情况下堆栈,Python steamlit 选择框菜单返回字符串,但我需要 dict 或 list,以便在我的代码中进一步使用它。我想在下拉菜单中查看 company1、company2、company3,如果用户的选择是例如 'company2' get ['ID': 'zxc222’, 'NAME': 'company2','DESC': 'comp2']

BaseObject = [{
    'ID': 'zxc123',
    'NAME': 'company1',
    'DESC': 'comp1'
}, {
    'ID': 'zxc222',
    'NAME': 'company2',
    'DESC': 'comp2'
}, {
    'ID': 'zxc345',
    'NAME': 'company3',
    'DESC': 'comp3'
}]

lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
    options.append((BaseObject[i])['NAME'])
st.selectbox('Subdivision:', options)

标签: pythonstreamlit

解决方案


您可以在dict之后进行转换selectbox

import streamlit as st

BaseObject = [{
    'ID': 'zxc123',
    'NAME': 'company1',
    'DESC': 'comp1'
}, {
    'ID': 'zxc222',
    'NAME': 'company2',
    'DESC': 'comp2'
}, {
    'ID': 'zxc345',
    'NAME': 'company3',
    'DESC': 'comp3'
}]

lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
    options.append((BaseObject[i])['NAME'])
choice = st.selectbox('Subdivision:', options)

chosen_base_object = None
for base_object in BaseObject:
    if base_object["NAME"] == choice:
        chosen_base_object = dict(base_object)

print(chosen_base_object)  # {'ID': 'zxc345', 'NAME': 'company3', 'DESC': 'comp3'}

推荐阅读