Python中如何提取嵌套字典列表内指定用户名对应的全部评论?
报错原因
Reviews字段对应的数据类型是列表,不是字典,你直接用字符串作为下标访问列表,就会触发TypeError: list indices must be integers or slices, not str错误。你之前的两种写法都跳了一层逻辑:需要先遍历每个商品拿到评论列表,再遍历评论列表做用户名匹配。另外你第一个写法里的变量名误写为clothess_list(多了一个s),也需要修正为正确的变量名clothes_list。
正确实现
基础循环写法(可读性高)
target_username = "username341" result = [] # 遍历所有商品 for item in clothes_list: # 遍历单个商品的所有评论 for review in item["Reviews"]: # 匹配用户名则加入结果 if review["User"] == target_username: result.append(review)
列表推导式写法(更简洁)
target_username = "username341" result = [review for item in clothes_list for review in item["Reviews"] if review["User"] == target_username]
输出结果
打印result即可得到你期望的内容:
[{'User': 'username341', 'Review': 'Some review 2', 'Score': 4}, {'User': 'username341', 'Review': 'Some review 4', 'Score': 7}]
内容的提问来源于stack exchange,提问作者M5RKED
相关产品推荐
相关产品推荐

