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

使用字典值更新Google Spreadsheet时遭遇TypeError: Object of type dict_values is not JSON serializable错误求助

问题分析与解决

首先,你遇到的TypeError: Object of type dict_values is not JSON serializable错误,根源是**total_value.values()返回的是Python的dict_values迭代器对象**,而gspread的update方法要求传入能被JSON序列化的数据(比如列表、字符串、数字这类基础类型),迭代器无法直接被JSON序列化,所以触发了这个错误。

除此之外,你的代码还有一些逻辑问题,比如多层循环导致重复添加列、错误地将所有值重复写入多个单元格,下面是修正后的完整方案:

1. 核心错误修复

把total_value.values()转换成可序列化的列表(比如list(total_value.values()))是基础,但更关键的是调整你的更新逻辑,避免无效循环和错误写入。

2. 修正后的完整代码

import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials

def colnum_string(n):
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

total_value = {'Others': 350831.04, 'Q-labs': 3119.02, 'Practice': 2026.24, 'Account': 1068.04, 'SUPPORT': 988.45, 'Aflac': 807.65, 'Central': 392.77, 'SAVINGS': 339.2, 'PLAN': 329.79, 'MCD': 305.29, 'DU': 139.35, 'Val': 135.69, 'TAX': 133.55, 'School': 100.38, 'Service': 97.59, 'Charges': 78.59}

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open('Data').worksheet('Daily-Data')

# 获取第一列所有内容(包含表头),构建key到行号的映射
all_col1 = sheet.col_values(1)
key_row_map = {key: idx+2 for idx, key in enumerate(all_col1[1:])}

# 添加一列新列并获取列字母
sheet.add_cols(1)
new_col = colnum_string(sheet.col_count)
# 更新新列的表头(可以改成日期等自定义内容)
sheet.update(f"{new_col}1", "testing")

# 遍历字典,精准更新对应行的数值
for key, value in total_value.items():
    if key in key_row_map:
        row_num = key_row_map[key]
        sheet.update(f"{new_col}{row_num}", value)

3. 关键修改点说明

  • 序列化问题解决:不再直接传递dict_values对象,而是遍历字典的键值对,直接传入单个可序列化的数值。
  • 逻辑优化:
    • 提前构建key_row_map映射表,避免多层嵌套循环,提升代码效率。
    • 只添加一次新列,避免每次匹配key就重复创建列的问题。
    • 精准定位每个key对应的行号,只更新目标单元格,避免批量写入错误内容。

这样修改后,既解决了JSON序列化的错误,也让你的更新逻辑更清晰、高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:57:34