将嵌套Python字典转Pandas DataFrame时出现‘无items属性’错误原因?
问题:SPSS ValueLabel对象转换为DataFrame时触发AttributeError
我通过SPSS的valueLabels属性获取了一个嵌套结构,存入变量nested_dict_variable中。type(nested_dict_variable)返回dict,print(nested_dict_variable)输出:
{0: {1.0: '1 - low', 2.0: '2', 3.0: '3', 4.0: '4', 5.0: '5 - high', 99.0: "99 - don't know"}, 1: {0.0: '0 - no', 1.0: '1 - yes'}, 2: {1.0: '1 - A', 2.0: '2 - B', 3.0: '3 - C'}}
但尝试将其转换为Pandas DataFrame时触发了属性错误,错误信息如下:
AttributeError Traceback (most recent call last) File c:\mypythonfile.py:38 36 data_list = [] 37 for outer_key, inner_dict in nested_dict_variable.items(): ---> 38 for inner_key, value in inner_dict.items(): 39 data_list.append({'Outer Key': outer_key, 'Inner Key': inner_key, 'Value': value}) 41 df = pd.DataFrame(data_list) AttributeError: 'ValueLabel' object has no attribute 'items'
我的代码如下:
# 从外部Python进程运行SPSS Statistics import spss import pandas as pd # 读取SPSS数据 file = r"C:\SPSS-SampleData1.sav" spss.Submit( f""" GET FILE='{file}'. """ ) var_index = [] nested_dict_variable= {} # 初始化SPSS命令处理 spss.StartDataStep() # 访问激活的数据集 datasetObj = spss.Dataset() # 获取变量对象列表 varListObj = datasetObj.varlist for var in varListObj: var_index.append(var.index) nested_dict_variable[var.index] = var.valueLabels spss.EndDataStep() ##### 创建DataFrame ##### # 将嵌套字典转换为Pandas DataFrame data_list = [] for outer_key, inner_dict in nested_dict_variable.items(): for inner_key, value in inner_dict.items(): data_list.append({'Outer Key': outer_key, 'Inner Key': inner_key, 'Value': value}) df = pd.DataFrame(data_list) # 结束SPSS进程 spss.StopSPSS()
解决方法
问题核心:var.valueLabels返回的不是普通Python字典,而是SPSS自定义的ValueLabel对象——虽然打印输出看起来和字典一致,但它没有标准字典的items()方法。
只需将每个ValueLabel对象转换为普通字典即可修复:
修改赋值代码行:
nested_dict_variable[var.index] = dict(var.valueLabels)
修改后的循环部分:
for var in varListObj: var_index.append(var.index) # 转换为标准Python字典 nested_dict_variable[var.index] = dict(var.valueLabels)
转换后,nested_dict_variable内存储的都是标准字典对象,后续遍历inner_dict.items()就不会触发属性错误了。
内容的提问来源于stack exchange,提问作者xChillout
相关产品推荐
相关产品推荐

