如何从SQL解析生成的字典列表中提取where键对应的值?
提取所有字典中where键对应的所有值
可以用两种方式实现,根据使用习惯选择:
方法一:列表推导式
直接通过嵌套列表推导式过滤无效数据并收集值:
where_values = [val for dic in df_1_joins_where if dic and 'where' in dic for val in dic['where']]
- 逻辑:先排除
augment返回的None值,再检查字典是否包含where键,最后遍历每个where对应的列表元素,将所有值收集到一个列表中。
方法二:Pandas 链式操作
利用Pandas的Series方法处理,更贴合数据分析场景:
where_values = df_1_joins_where.dropna() \ .apply(lambda x: x.get('where', [])) \ .explode() \ .tolist()
- 逻辑:
dropna():移除Series中值为None的元素apply(lambda x: x.get('where', [])):提取每个字典的where值,没有则返回空列表explode():将列表类型的元素拆分成单独的行tolist():将最终的Series转换为普通列表
内容的提问来源于stack exchange,提问作者python_pi
相关产品推荐
相关产品推荐

