如何解释字符串以定义字典调用? [英] How to interpret a string to define a dictionary call?

查看:68
本文介绍了如何解释字符串以定义字典调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试传递给函数,该函数将被解释为确定更新字典所需的所需字典调用的字符串.

I am attempting to pass in to a function, a string which will be interpreted to determine the desired dictionary call required to update a dictionary.

以下是我到目前为止硬编码的示例:

Here is an example of what I have so far, hard-coded:

import json
from collections import defaultdict

def default_dict():
    return defaultdict(default_dict)

def build_dict():
    d["a"]["b"]["c"]["d"]["e"]["f"].update({})
    d["a"]["b"]["c1"]["d1"].update({})
    return json.dumps(d)

d = default_dict()
print build_dict()

但是为了对我有用,我想将字符串传递给build_dict()函数.让我们称之为"s":

But to be useful to me I want to pass in strings to the build_dict() function. Lets call it 's':

for s in ["a/b/c/d/e/f", "a/b/c1/d1"]:
    print build_dict(s)

应打印以下内容(与我硬编码的示例中的内容完全相同:

Which should print the following (exactly as it does in the example I hard-coded:

{
    "a": {
        "b": {
            "c": {
                "d": {
                    "e": {
                        "f": {}
                    }
                }
            },
            "c1": {
                "d1": {}
            }
        }
    }
}

在我的硬编码示例中,我必须确保以我所测试的方式支持多个分支.

I have to make sure that multiple branches are supported in the way they are (as far as I have tested) in my hard-coded example.

我目前正在尝试什么:

  • 通过构造这个问题的中途,我发现了关于dpath的信息,一个通过/slashed/paths ala xpath访问和搜索字典的python库".它看起来正是我需要的,因此,如果我成功解决了该问题,我将发布该问题的答案.

推荐答案

我为自己的问题制定了解决方案.

I worked out a solution to my own question.

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 = [
    "a/b/c/d/e/f",
    "a/b/c1/d1"
]

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

这篇关于如何解释字符串以定义字典调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆