将嵌套字典转换为字符串

时间:2018-04-30 21:54:25

标签: python python-2.7 dictionary recursion

我正在努力实现以下目标:

app.get('/super', async function(req, res){
    try {
        res.send(await config.options());
//               ^^^^^
    } catch(e) {
        // TODO: error handling
    }
});

输出=

1)当value是字典时,则创建一个输出字符串variable =

Input = {
    'key1':{'key11':'val11', 'key12':'val12'},
    'key2':{'key21':{'key211':'val211', 'key212':'val212'}},
    'key3':'val3',
    'key4':{'key41':'val41', 'key42':'val42'}
}

2)当值不是字典时,请打印key1 { key11 val11 key12 val12 } key2 { key21 { key211 val211 key212 val212 }} key4 { key41 val41 key42 val42}

以下是我的代码:

"just a string element"

以下是我得到的输出:

from collections import defaultdict

def stringBuilder(dictionary):
    stringOption = ""
    innerString = ""
    # print dictionary
    for key, value in dictionary.iteritems():
        if isinstance(value, dict):
            stringBuilder(value)
        else:
            innerString = innerString + " " + str(key) + " " + str(value)
            print innerString
            stringOption = "{" + innerString + " }"
            print stringOption
    return stringOption

d = {'key1':{'key11':'val11', 'key12':'val12'}, 'key2':{'key21':{'key211':'val211', 'key212':'val212'}}, 'key3':'val3', 'key4':{'key41':'val41', 'key42':'val42'}}
print d
stringOption = ""
for key, value in d.iteritems():
    if isinstance(value, dict):
        stringOption = stringOption + " " + str(key) + " " + stringBuilder(value)
        print stringOption
    else:
        print "just a string element"
print stringOption

3 个答案:

答案 0 :(得分:1)

一次很棒的递归练习!

def rec(x):
    # assuming values are either str or otherwise dict
    if isinstance(x, str):
        return x
    return '{' + ' '.join([k + ' ' + rec(v) for (k, v) in x.items()]) + '}'


Input = {
    'key1':{'key11':'val11', 'key12':'val12'},
    'key2':{'key21':{'key211':'val211', 'key212':'val212'}},
    'key3':'val3',
    'key4':{'key41':'val41', 'key42':'val42'}
}

输出:

In [6]: rec(Input)
Out[6]: '{key1 {key11 val11 key12 val12} key2 {key21 {key211 val211 key212 val212}} key3 val3 key4 {key41 val41 key42 val42}}'

答案 1 :(得分:0)

您的主要问题是您丢弃了dict案例的返回字符串:

    if isinstance(value, dict):
        stringBuilder(value)

相反,请尝试保存该值以传回该行:

    if isinstance(value, dict):
        stringOption = stringBuilder(value)

结果输出:

key2 { key211 val211 key212 val212 } key1 { key12 val12 key11 val11 } key4 { key41 val41 key42 val42 }

答案 2 :(得分:0)

不是编写自己的实现(除非那是你想要的)为什么不使用json library?您可以扩展JSONEncoder和JSONDecoder以适合您的使用案例吗?