Python嵌套字典数据提取:提取result内字典的start与word值
提取Python字典中指定键值的方法
没问题!要提取result列表里每个子字典的start和word,有几种简洁的实现方式,咱们来一步步看:
首先先把你的原始数据放出来,方便参考:
data = { "result" : [ { "conf" : 1.000000, "end" : 105.570000, "start" : 104.970000, "word" : "today" }, { "conf" : 1.000000, "end" : 106.320000, "start" : 106.080000, "word" : "yes" }, { "conf" : 1.000000, "end" : 106.590000, "start" : 106.320000, "word" : "sir" } ], "text" : "today yes sir" }
方法一:for循环遍历(直观易懂)
如果需要清晰的步骤,方便后续加额外操作,普通循环就很合适:
# 初始化空列表存储结果 extracted_data = [] # 遍历result中的每个字典元素 for item in data["result"]: # 提取start和word,组装成新字典 extracted_item = { "start": item["start"], "word": item["word"] } extracted_data.append(extracted_item) # 查看结果 print(extracted_data)
运行后会得到:
[{'start': 104.97, 'word': 'today'}, {'start': 106.08, 'word': 'yes'}, {'start': 106.32, 'word': 'sir'}]
方法二:列表推导式(简洁高效)
要是追求代码紧凑,Python的列表推导式一行就能搞定,这也是开发者常用的写法:
# 提取为字典格式 extracted_data = [{"start": item["start"], "word": item["word"]} for item in data["result"]] # 也可以存成元组,写法更简单: # extracted_data = [(item["start"], item["word"]) for item in data["result"]] print(extracted_data)
这个结果和循环方法完全一致,只是写法更精炼。
核心逻辑其实很简单:先通过data["result"]拿到目标列表,再逐个访问列表里的字典元素,最后通过键名start和word提取对应的值即可。
内容的提问来源于stack exchange,提问作者Srijan Biswas
相关产品推荐
相关产品推荐

