Python脚本将SAP数据提取至AWS Glue时遇'unhashable type: dict'错误
问题排查与解决
错误根源
错误"unhashable type: 'dict'"出现在创建Pandas DataFrame的环节。pyrfc调用RFC_READ_TABLE后返回的FIELDS是字典数组(每个字典包含FIELDNAME等属性),而非直接的字符串列名,直接将其传给pd.DataFrame的columns参数会触发该错误——因为字典属于不可哈希类型,无法作为列名使用。
修复步骤
- 提取纯字符串列名:从
FIELDS字典数组中提取FIELDNAME字段值,生成字符串类型的列名列表 - 拆分行数据:
DATA返回的每行是包含WA键的字典,需将WA值按指定分隔符拆分,匹配对应列名 - 修正RFC参数格式:pyrfc要求
FIELDS参数为字典列表(每个字典含FIELDNAME键),原脚本的字符串列表不符合规范
修正后的完整脚本
from pyrfc import Connection import pandas as pd ## Variables sap_table = 'TABLENAME' # SAP Table Name fields = ["FIELD1", "FIELD2"] # List of fields options = [""] max_rows = 10 from_row = 0 delimiter = '|' try: # Establish SAP RFC connection conn = Connection(ashost='mysapserver.com', sysnr='00', client='000', user='username', passwd='password') print(f"SAP Connection successful – connection object: {conn}") if conn: # Read SAP Table information tables = conn.call( "RFC_READ_TABLE", QUERY_TABLE=sap_table, DELIMITER=delimiter, FIELDS=[{"FIELDNAME": field} for field in fields], OPTIONS=options, ROWCOUNT=max_rows, ROWSKIPS=from_row ) # 提取字段名列表 columns = [field["FIELDNAME"] for field in tables["FIELDS"]] # 拆分每行的WA数据为列值 data_rows = [row["WA"].split(delimiter) for row in tables["DATA"]] df = pd.DataFrame(data_rows, columns=columns) if not df.empty: print(f"Successfully extracted data from SAP using custom RFC - Printing the top 5 rows:\n{df.head(5)}") else: print("No data returned from the request. Please check database/schema details") else: print("Unable to connect with SAP. Please check connection details") except Exception as e: print(f"An exception occurred while connecting with SAP system: {e.args}")
额外注意事项
- 若字段值本身包含分隔符
|,拆分时会出错,建议选用SAP数据中不存在的字符作为分隔符(如~) RFC_READ_TABLE返回的所有数据均为字符串类型,需根据业务需求自行转换字段类型(如数字、日期)
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

