过滤具有不同类型值的字典

问题描述 投票:0回答:1

我试图按值过滤字典(具有不同数据类型的字典),但收到错误:

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

我想获取字典中与“YALE”值对应的所有记录。

这是我的代码:

dataset = {
    'timeseires': array([[
        [ -5.653222,   7.39066 ,  20.651941, 4.07861 ,-11.752331, -34.611312],
        [ -5.653222,   7.39066 ,  20.651941, 4.07861 ,-11.752331, -34.611312]
    ]]),
    'site': array(['YALE', 'KKI'], dtype='<U8')
}

dataset = data.tolist()
 
def filter(pairs):
    key, value = pairs
    filter_key = 'site'
    if key == filter_key and value == 'YALE':
        return True
    else:
        return False
         
final_dic = dict(filter(filter, dataset.items()))
print(final_dic)

预期产出:

> dataset = {
>         'timeseires': array([[
>             [ -5.653222,   7.39066 ,  20.651941, 4.07861 ,-11.752331, -34.611312]
>         ]]),
>         'site': array(['KKI'], dtype='<U8')
>     }
python numpy dictionary filter
1个回答
0
投票

从给出的输出来看,您的任务似乎是提取与

'timeseries'
的索引相对应的
'YALE'
值。

这段代码应该可以解决问题:

def filter_dictionary_by_value(dataset, value):
    index_value = np.where(dataset['site'] == value)[0]
    filtered_timeseries = dataset['timeseries'][index_value]
    

    filtered_dict = {
        'timeseries': filtered_timeseries,
        'site': np.array([value], dtype='<U8')
    }

如果这不是您所期望的,请在问题中更加具体。

© www.soinside.com 2019 - 2024. All rights reserved.