【问题标题】:Google Sheets API - Python - Constructing Body for BatchUpdateGoogle Sheets API - Python - 为 BatchUpdate 构建正文
【发布时间】:2018-08-16 19:45:17
【问题描述】:

我需要使用 Python 为 Google 电子表格的多次更新创建正文。

我使用了 Python 字典 dict(),但这不适用于重复的多个值,因为 dict() 不允许多个键。

我的代码 sn-p 是:

body = {
       }
for i in range (0,len(deltaListcolNames) ):
        rangeItem = deltaListcolNames[i]

        batch_input_value = deltaListcolVals[i]

        body["range"] = rangeItem
        body["majorDimension"] =  "ROWS"
        body["values"] = "[["+str(batch_input_value)+"]]"




batch_update_values_request_body = {
# How the input data should be interpreted.
  'value_input_option': 'USER_ENTERED',   

 # The new values for the input sheet...   to apply to the spreadsheet.
  'data': [
   dict(body)

          ]
}  

print(batch_update_values_request_body)
request = service.spreadsheets().values().batchUpdate(
    spreadsheetId=spreadsheetId, 
    body=batch_update_values_request_body)

response = request.execute()

【问题讨论】:

    标签: python api dictionary


    【解决方案1】:

    感谢您的回答,格雷厄姆。 我翻了一番,不再使用 dict 范式,发现通过使用这个网格,我能够制作数据结构。这是我的编码方式... 也许有点古怪,但效果很好:

    range_value_data_list = []
    
    width = 1
    #
    height = 1
    for i in range (0,len(deltaListcolNames) ):
            rangeItem = deltaListcolNames[i]
            # print(" the value for rangeItem is : ", rangeItem)
            batch_input_value = str(deltaListcolVals[i])
            print(" the value for batch_input_value is : ", batch_input_value)
            # construct the data structure for the value
            grid = [[None] * width for i in range(height)]
            grid[0][0] = batch_input_value
    
            range_value_item_str = { 'range': rangeItem, 'values': (grid) }
            range_value_data_list.append(range_value_item_str)
    

    【讨论】:

      【解决方案2】:

      查看Python client library methods 的文档:data 部分是 dict 对象的列表。

      所以你的构造很接近,你只需要一个填充数据列表的循环:

      data = []
      for i in range(0, len(deltaListcolNames)):
          body = {}
          # fill out the body
          rangeItem = deltaListcolNames[i]
          ....
      
          # Add this update's body to the array with the other update bodies.
          data.append(body)
      
      # build the rest of the request
      ...
      # send the request
      ...
      

      【讨论】:

        猜你喜欢
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 2021-05-21
        相关资源
        最近更新 更多