Python中提取嵌套字典内Analytical Properties字段问题求助
解决嵌套字典列表中提取所有'Analytical Properties'的问题
你的psets并非单个字典,而是包含两个字典的列表(原数据写法缺少外层列表的[],属于语法错误,需要先修正)。之前的代码仅遍历了第一个字典的键值对,完全没处理第二个字典,因此只能获取到一个结果。
修正后的代码
常规循环写法
all_properties = [] # 遍历列表中的每个字典元素 for item in psets: # 检查当前字典是否包含目标键 if 'Analytical Properties' in item: all_properties.append(item['Analytical Properties']) print(all_properties)
简洁列表推导式写法
all_properties = [item['Analytical Properties'] for item in psets if 'Analytical Properties' in item] print(all_properties)
修正原始数据格式
你的原始psets定义存在语法错误,需要给两个字典套上外层列表[],正确格式如下:
psets = [ {'Windows_Alumil_Supreme_S77_PHOS_Fixed:Windows_Alumil_S77_Fixed_9_triple_glazing:1016843': {'id': 66476}, 'Analytical Properties': {'Analytic Construction': '', 'Define Thermal Properties by': 'User Defined', 'Heat Transfer Coefficient (U)': 1.63, 'Solar Heat Gain Coefficient': 0.27, 'Thermal Resistance (R)': 0.6134969325153374, 'Visual Light Transmittance': 0.74, 'id': 66617}, 'Construction': {'Construction Type': 'Window', 'Wall Closure': 'By host', 'id': 66618}, 'Dimensions': {'Height': 0.55, 'Rough Height': 2.115, 'Rough Width': 0.5650000000000001, 'Width': 2.1, 'Window Inset Depth': 0.01, 'id': 66619}}, {'Windows_Alumil_Supreme_S77_PHOS_Fixed:Windows_Alumil_S77_Fixed_8_triple_glazing:1016844': {'id': 68543}, 'Analytical Properties': {'Define Thermal Properties by': 'User Defined', 'Analytic Construction': '', 'Heat Transfer Coefficient (U)': 1.94, 'Solar Heat Gain Coefficient': 0.19, 'Thermal Resistance (R)': 0.5154639175257733, 'Visual Light Transmittance': 0.74, 'id': 68666}, 'Construction': {'Wall Closure': 'By host', 'Construction Type': 'Window', 'id': 68667}, 'Dimensions': {'Height': 0.55, 'Rough Height': 0.5650000000000001, 'Rough Width': 0.5650000000000001, 'Width': 0.55, 'Window Inset Depth': 0.01, 'id': 68668}} ]
内容的提问来源于stack exchange,提问作者Talha Siddiqui
相关产品推荐
相关产品推荐

