You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataFrame转换为值为列表的字典用于SQL表更新

DataFrame转指定格式字典的实现方案

现有输入与需求

  • 待处理的DataFrame结构如下:
IDAB
case1%case description1
case2abcase description2
case3ghcase description3
case4sgcase description4
  • 目标输出为ID做键、A/B列值组成的列表做值的字典,格式参考:
{
    'case1': ['%', 'case description1'],
    'case2': ['ab', 'case description2'],
    'case3': ['gh', 'case description3'],
    'case4': ['sg', 'case description4']
}

注:你给出的预期示例存在语法错误:字符串类型的键未加引号、case3对应的B值字符串缺少闭合引号,Python中合法的字典字符串键值必须包裹在引号中。

  • 转换后的字典将传入以下函数用于SQL库表更新:
def update_units(source_dictionary,tag_list):
    for ID in id_list:
      key=ID
      value1=(source_dictionary[ID][1] if ID in source_dictionary else None)
      value2=(source_dictionary[ID][2] if ID in source_dictionary else None)
      
      session.query(table1).filter(table1.Id == key).update(
                {
                    "A": value1,
                    "B": value2
                }
            )
    session.commit()

注意:上述更新函数存在索引错误:Python列表索引从0开始计数,你要取的A值是列表第1个元素对应索引0,B值是列表第2个元素对应索引1,原代码写的[1]/[2]会触发索引越界,或是取错值,使用时需要修正。

转换实现代码

两种常用实现方式,按需选择即可:

方式1:逐行遍历生成(逻辑直观,适合小数据量)

# 假设你的原始DataFrame变量名为df
result_dict = {}
for _, row in df.iterrows():
    result_dict[row['ID']] = [row['A'], row['B']]

方式2:pandas内置方法生成(性能更高,适合万行以上大表)

# 将ID列设为行索引后,按行把列值转为列表,最后直接输出为字典
result_dict = df.set_index('ID').agg(list, axis=1).to_dict()

使用说明

转换得到的result_dict可以直接传入修正索引后的update_units函数使用,不需要额外做格式调整。

内容的提问来源于stack exchange,提问作者MMV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 22:45:38