将点分隔的字符串解析为字典变量

2 python string dictionary

我的字符串值为,

"a"
"a.b"
"b.c.d"
Run Code Online (Sandbox Code Playgroud)

如何将它们转换为Python字典变量,

a
a["b"]
b["c"]["d"]
Run Code Online (Sandbox Code Playgroud)

字符串的第一部分(点之前)将成为字典名称,其余子字符串将成为字典键

iJa*_*mes 5

我在解析不同部分中具有点分隔键的 ini 文件时遇到了同样的问题。例如:

[app]
site1.ftp.host = hostname
site1.ftp.username = username
site1.database.hostname = db_host
; etc..
Run Code Online (Sandbox Code Playgroud)

所以我写了一个小函数来将“add_branch”添加到现有的字典树中:

def add_branch(tree, vector, value):
    """
    Given a dict, a vector, and a value, insert the value into the dict
    at the tree leaf specified by the vector.  Recursive!

    Params:
        data (dict): The data structure to insert the vector into.
        vector (list): A list of values representing the path to the leaf node.
        value (object): The object to be inserted at the leaf

    Example 1:
    tree = {'a': 'apple'}
    vector = ['b', 'c', 'd']
    value = 'dog'

    tree = add_branch(tree, vector, value)

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog'}}}

    Example 2:
    vector2 = ['b', 'c', 'e']
    value2 = 'egg'

    tree = add_branch(tree, vector2, value2)    

    Returns:
        tree = { 'a': 'apple', 'b': { 'c': {'d': 'dog', 'e': 'egg'}}}

    Returns:
        dict: The dict with the value placed at the path specified.

    Algorithm:
        If we're at the leaf, add it as key/value to the tree
        Else: If the subtree doesn't exist, create it.
              Recurse with the subtree and the left shifted vector.
        Return the tree.

    """
    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
Run Code Online (Sandbox Code Playgroud)

  • 超级有帮助。我将其用作交叉,供人们使用和 excel 工作表,其中包含以此模式标记的列,以便我可以进行批量 api 调用,尽管我需要在逻辑中添加一些内容以使其正常工作: rowObj.update(add_branch (rowObj,colName.split("."),rowValue)) (2认同)