Skip to main content
 首页 » 编程设计

python 和 Pandas : Find a dict within a list according to a key's value

2024年10月17日6artech

我有一个如下所示的列表:

dict_list = [{'angle': 5.0, 
              'basic_info': '111', 
              'x': [1,2,3,4], 
              'y': [3,2,1,4],}, 
            {'angle': 25.0, 
              'basic_info': '111', 
              'x': [1,2,3,4], 
              'y': [3,1,5,2],}, 
            {'angle': 3.0, 
              'basic_info': '111', 
              'x': [1,2,3,4], 
              'y': [1,1,4,1],},] 

我想得到 dict 角度 25,我该怎么做?


更新:

在玩了一段时间 Pandas 之后,我发现这可能是可行的

df = pd.DataFrame(dict_list) 
temp = df.query("(angle ==25 )").T.to_dict()[temp.keys()[0]] 
temp 

返回

{'angle': 25.0, 'basic_info': '111', 'x': [1, 2, 3, 4], 'y': [3, 1, 5, 2]} 

但这有点hack。

请您参考如下方法:

假设字典中的每个角度都是唯一的,并且每个字典都包含键“角度”:

df = None 
for sub_dict in dict_list: 
    if sub_dict['angle'] == 25: 
        df = pd.DataFrame({'x': sub_dict['x'], 'y': sub_dict['y']}) 
        break  # Stops after finding the first matching angle. 
if df is not None: 
    df.plot(x='x', y='y')