小编Ane*_*way的帖子

使用字典和数组将点符号字符串转换为嵌套的 Python 对象

背景

对于某些背景,我正在尝试创建一个使用 Python 3.5 将工作表转换为 API 调用的工具

为了将表格单元格转换为 API 调用所需的模式,我已经开始对电子表格中使用的标题使用类似 javascript 的语法。例如:

工作表标题(字符串)

dict.list[0].id
Run Code Online (Sandbox Code Playgroud)

Python字典

{
  "dict":
    "list": [
      {"id": "my cell value"}
    ]
}
Run Code Online (Sandbox Code Playgroud)

标头架构也可能具有嵌套的数组/字典:

one.two[0].three[0].four.five[0].six
Run Code Online (Sandbox Code Playgroud)

而且我还需要在创建对象后附加到对象,因为我浏览每个标题。

我试过的

添加分支

基于/sf/answers/3309354331/,我可以使用类似的值设置嵌套字典,one.two.three.four并且我可以在浏览行时附加到现有字典,但我一直无法添加对数组的支持:

def add_branch(tree, vector, value):
    key = vector[0]
    tree[key] = value \
        if len(vector) == 1 \
        else add_branch(tree[key] if key in tree else {},
                        vector[1:],
                        value)
    return tree

file = Worksheet(filePath, sheet).readRow()
rowList = []
for row in file:
    rowObj = {}
    for colName, rowValue …
Run Code Online (Sandbox Code Playgroud)

python arrays dictionary python-3.x

5
推荐指数
1
解决办法
2121
查看次数

标签 统计

arrays ×1

dictionary ×1

python ×1

python-3.x ×1