如何将字典中嵌套的字典列表转换为仅含指定值的列表
Python提取字典列表指定字段的实现方法
核心思路
使用Python的列表推导式遍历外层字典中存储的子字典列表,逐个取出指定字段的值组装成新列表,写法简洁效率高。
单字段提取示例
以你提供的示例数据为例,若要提取所有close字段的值,代码如下:
dictionary = { "candles":[ { "open": 78.21, "high": 78.28, "low": 78.12, "close": 78.2, "volume": 16417, "datetime": 1620385200000 }, { "open": 78.19, "high": 78.26, "low": 78.17, "close": 78.2, "volume": 5928, "datetime": 1620387000000 } ] } # 提取所有close字段值 close_list = [item["close"] for item in dictionary["candles"]]
运行后close_list的结果为[78.2, 78.2]。
多字段提取示例
如果需要同时提取多个字段,可按如下写法实现:
# 提取open和datetime两个字段,每个元素为字典格式 target_list = [{"open": item["open"], "datetime": item["datetime"]} for item in dictionary["candles"]]
运行后target_list的结果为:[{'open': 78.21, 'datetime': 1620385200000}, {'open': 78.19, 'datetime': 1620387000000}]
注意事项
如果不确定子字典中是否存在目标字段,可使用字典的get方法设置默认值,避免抛出KeyError异常:
# 若子字典无close字段,默认返回0 close_list = [item.get("close", 0) for item in dictionary["candles"]]
内容的提问来源于stack exchange,提问作者mospira
相关产品推荐
相关产品推荐

