如何将斜杠分隔字符串列表转换为嵌套字典?

时间:2015-11-25 13:54:34

标签: regex python-2.7 parsing dictionary

我有以下格式的数据列表:

viewsList = [
  "/list/devicetype",
  "/list/client/devicetype",
  "/list/client/site/devicetype",
  "/list/privileges",
  "/list/client/serviceusage",
  "/list/client/site/serviceusage",
  "/list/client/license"
]

除此之外,我想以下列格式创建一个字典:

viewsDict = {
    "list": {
        "devicetype": {},
        "client": {
            "devicetype": {},
            "site": {
                "devicetype": {},
                "serviceusage": {}
            },
            "serviceusage": {},
            "license": {}
        },
        "privileges": {}
    }
}

到目前为止我尝试了什么:

我已经显示了下面的代码,以便它成功执行。它打印出我思考过程的第一步。

如果我设法生成7个单独的词典,一个用于'viewsList'中的每个元素,那么我是否能够合并所有这些词典而不会覆盖?:

def url_views():
    viewsList = [
        "/list/devicetype",
        "/list/client/devicetype",
        "/list/client/site/devicetype",
        "/list/privileges",
        "/list/client/serviceusage",
        "/list/client/site/serviceusage",
        "/list/client/license"
    ]    
    viewsDict = {}
    for eachView in viewsList:
        #viewsDict.update(...
        build_dict(eachView[1:].split("/")) #) I know update() won't work here 
                                               # because it will just overight
                                               # keys which are supposed to have
                                               # multiple nested dictionaries 

def build_dict(eachViewSplit):

    # Need to do something here to convert each line into a dictionary
    print eachViewSplit # Printing this line for diagnostics purposes
    #return buildDict


print url_views()

运作逻辑:

我已经找到了我需要的逻辑,我需要帮助的是如何编写这些步骤:

>>> viewsDict = {}
>>> viewsDict["list"] = {}
>>> viewsDict["list"]["devicetype"] = {}
>>> viewsDict["list"]["client"] = {}
>>> viewsDict["list"]["client"]["devicetype"] = {}
>>> viewsDict["list"]["client"]["site"] = {}
>>> viewsDict["list"]["client"]["site"]["devicetype"] = {}
>>> viewsDict["list"]["privileges"] = {}
>>> viewsDict["list"]["client"]["serviceusage"] = {}
>>> viewsDict["list"]["client"]["site"]["serviceusage"] = {}
>>> viewsDict["list"]["client"]["license"] = {}
>>> print viewsDict

这会打印出与上面列出的字典相当的字典。

2 个答案:

答案 0 :(得分:1)

这应该有效:

def parse(lines):
    result = dict()

    for line in lines:
        cur_dict = result
        for field in line.strip("/").split("/"):
            cur_dict = cur_dict.setdefault(field, {})

    return result

dict.setdefault相当于:

def setdefault(self, key, default):
    try:
        return self[key]
    except KeyError:
        self[key] = default
        return default

因此,对于" /" -delimited字符串中的每个字段,我们会深入到字典中并在适当的位置创建空字符串。然后,当我们回到下一行时,我们从根开始。

答案 1 :(得分:0)

我为自己的问题制定了另一种解决方案。

import json
import dpath.util

def build_dict(viewsDict, viewsList):
    for views in viewsList:
        viewsDict = new_keys(viewsDict, views)
    return viewsDict

def new_keys(viewsDict, views):
    dpath.util.new(viewsDict, views, {})
    return viewsDict

viewsDict = {}
viewsList = [
    "/list/devicetype",
    "/list/client/devicetype",
    "/list/client/site/devicetype",
    "/list/privileges",
    "/list/client/serviceusage",
    "/list/client/site/serviceusage",
    "/list/client/license"
]

print json.dumps(build_dict(viewsDict, viewsList), indent=4, sort_keys=True)