gpt4 book ai didi

python - 如何使用 Jupyter Widgets 创建依赖下拉列表以从 dict 获取数据?

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:03 24 4
gpt4 key购买 nike

我正在尝试使用 Jupyter Dropdowns 为两个变量分配值,其中第一个下拉列表是一个数据中心,第二个是该数据中心内可用的站点,以便我可以在代码中进一步使用这些变量。

我尝试了不同文章中的多个示例,但找不到我缺少的内容。

我有以下字典:

data_center_environments = {
'US': {
'data_center': 'us..com',
'api_keys': {
'sandbox' : '3_EV',
'dev_parent' : '3_hK',
'stage' :'3_GE',
'prod' : '3_NL',
}
},
'RU': {
'data_center': 'ru..com',
'api_keys': {
'stage_parent' : '3_sN',
'prod_parent' : '3_R9',
}
},
'CN': {
'data_center': 'cn..cn',
'api_keys': {
'stage_parent' : '3_3k',
'prod_parent' : '3_MH',
}
},
'EU': {
'data_center': 'eu..com',
'api_keys': {
'sandbox' : '3_7h',
}
},
}

我创建了两个函数来获取数据中心和站点:

def get_dc(dc_select=None):
dc = data_center_environments.get(dc_select)['data_center']
return dc

def get_site_api_key(dc_select=None, site_select=None):
site_api_key = data_center_environments[dc_select]['api_keys'][site_select]
return site_api_key

这里我描述了两个下拉菜单:

dc_s = widgets.Dropdown(
options = data_center_environments.keys(),
description = 'Data Center:',
disabled = False,
)

site_s = widgets.Dropdown(
options=list(data_center_environments[dc_s.value]['api_keys']),
description = 'API Key:',
disabled = False,
)


def on_value_change(change):
dc = change.new
site_s.options = data_center_environments[dc_s.value]['api_keys']

dc_s.observe(on_value_change, 'value')

这就是我在 Jupyter Notebook 页面上调用它们的方式:

domain = interactive(get_dc, dc_select = dc_s)
site = interactive(get_site_api_key, dc_select = dc_s, site_select = site_s)
display(domain)
display(site)

问题:0. 我有 3 个下拉菜单而不是两个1. 更改数据中心值时出现异常2. 当我尝试打印“domain”、“domain.value”时,我得到的输出是“None”

我想要达到的目标:在:域名=网站=打印(域,站点)

输出:选择数据中心 [下拉:'US'、'CN'、'RU' 等] -> 选择'US'选择站点 [Dropdown 'US': 'prod', 'stage', 'dev_parent', 'sandbox'] -> 选择 'prod'

'us..com' , '3_NL'

我做错了什么?如何更改我的代码以使其工作?谢谢!

最佳答案

我最终编写了一个返回字典的函数,我只是从中获取值。下面的代码是 Widgets Guide 中的教科书示例。

解决方法:

dc = 'US'
domain = widgets.Dropdown(
options = list(data_center_environments),
description = 'Data Center:',
disabled = False,
)

site = widgets.Dropdown(
options=list(data_center_environments[dc]['api_keys']),
description = 'API Key:',
disabled = False,
)

def on_value_change(change):
dc = change.new
site.options = data_center_environments[dc]['api_keys']

domain.observe(on_value_change, 'value')

def creds(data_center, api_key, use_secret):
data_center = data_center_environments[domain.value]['data_center']
api_key = site.value
creds = dict()
creds['data_center'] = data_center
creds['api_key'] = api_key
return creds

关于python - 如何使用 Jupyter Widgets 创建依赖下拉列表以从 dict 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com