Python中无法从嵌套字典列表结构中获取指定asset的free值该如何解决?
错误原因
你调用的balance["balances"]返回的是列表类型,列表只能用整数下标/切片作为索引,你直接传入字符串'asset'作为列表索引,才会触发TypeError: list indices must be integers or slices, not str报错。
解决方法
方法1:已知列表位置时直接用索引取值
你给出的示例中asset:B对应的是列表的第2个元素,对应索引为1,可直接取值:
print(balance["balances"][1]["free"])
注意:该方法仅适用于
balances列表元素顺序固定的场景,顺序变更后取值会出错。
方法2:通用遍历匹配(推荐)
不管列表顺序怎么变,都可以通过遍历匹配asset字段的方式拿到对应值,不会受列表排序影响:
# 遍历匹配asset为B的条目 for item in balance["balances"]: if item["asset"] == "B": print(item["free"]) break
也可以用生成器表达式简化写法:
target_free = next(item["free"] for item in balance["balances"] if item["asset"] == "B") print(target_free)
如果要避免匹配不到值抛出StopIteration错误,可以给next方法加默认值:
target_free = next((item["free"] for item in balance["balances"] if item["asset"] == "B"), None) print(target_free)
内容的提问来源于stack exchange,提问作者user572575
相关产品推荐
相关产品推荐

