基于特定条件提取dictionary列表中的dictionary-python



我有一个字典,如下所示

d4 = {
"blue": 
[
{
"type": "linear",
"start_date": "2020-10-01T20:00:00.000Z",
"end_date": "2020-10-20T20:00:00.000Z",
"n_days":3,
"coef":[0.1,0.1,0.1,0.1,0.1,0.1],
"case":"worst"
}],
'cate' : 'C',
'prob': 0.2

}

d5 = {
"white": 
[
{
"type": "constant",
"start_date": "2020-10-08T20:00:00.000Z",
"end_date": "2020-10-25T20:00:00.000Z",
"n_days":18,
"coef":[0.1,0.1,0.1,0.1,0.1,0.1],
"case":"best"
}],
'cate' : 'A',
'prob': 0.3

}

根据上面的内容,我想写一个函数,它应该在"blue"或"white"键内返回dictionary。

功能可能类似于

def dict_inside_blue_or_white(d):

预期输出:

  1. 如果d4是上述函数的输入

    dict_inside_blue_or_white(d4(

应给出

{
"type": "linear",
"start_date": "2020-10-01T20:00:00.000Z",
"end_date": "2020-10-20T20:00:00.000Z",
"n_days":3,
"coef":[0.1,0.1,0.1,0.1,0.1,0.1],
"case":"worst"
}
  1. 如果d5是功能的输入

    dict_inside_blue_or_white(d5(

应给出如下所示的输出。

{
"type": "constant",
"start_date": "2020-10-08T20:00:00.000Z",
"end_date": "2020-10-25T20:00:00.000Z",
"n_days":18,
"coef":[0.1,0.1,0.1,0.1,0.1,0.1],
"case":"best"
}

我尝试了低于代码

def dict_inside_blue_or_white(d):
for i in ['blue'] or ['white']:
return d[i][0]

它适用于d4。但如果我通过d5,那么它给出的误差如下。

KeyError: 'blue'

看看这一行:

for i in ['blue'] or ['white']

这就是问题所在。它将被评估为['blue']。因为CCD_ 4确实,您可以使用print(['blue'] or ['white'])来查看结果。

对于您的情况,您可以使用:

def dict_inside_blue_or_white(d):
for i in ['blue', 'white']:
if i in d:
return d[i][0]

对于"蓝色";以及";白色";这是功能:

def dict_inside_blue_or_white(d):
for element in d:
if element in ["blue", "white"]:
dic=d[element][0]
return dic

以及输出,例如d4:

print(dict_inside_blue_or_white(d4))
{'type': 'linear','start_date': '2020-10-01T20:00:00.000Z','end_date': '2020-10-20T20:00:00.000Z', 'n_days': 3, 'coef': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1], 'case': 'worst'}

如果你喜欢单行,那么试试这个非常简单的片段。

def dict_inside_blue_or_white(d):
x = [d.get(item) for item in ['blue', 'white'] if item in d]
return x[0][0]
print(dict_inside_blue_or_white(d5))

相关内容

  • 没有找到相关文章

最新更新