从Python字典创建文件'like string'

时间:2016-06-19 15:16:14

标签: python dictionary recursion

我找到了一个在这个论坛上递归迭代python字典对象的方法。但是,我希望扩展该函数,以便获得类似于文件路径结构的字符串。使用下面的函数,我希望以

的形式输出
/key1/value1
/key2/value2
/key3/key3a/value3a
/key4/key4a/key4a1/value4a1
/key4/key4a/key4a2/value4a2
/key4/key4a/key4a3/value4a3
/key4/key4b/key4b1/key4b1a/value4b1a
/key4/key4b/key4b1/key4b1b/value4b1b
/key4/key4b/key4b1/key4b1c/value4b1c
/key4/key4c/key4c1/key4c1a/value4c1a
/key4/key4c/key4c1/key4c1b/value4c1b
/key4/key4c/key4c1/key4c1c/value4c1c

不幸的是,我遇到了障碍。我无法弄清楚如何实现这一目标。下面是我提出的代码。非常感谢任何帮助。

import sys
import collections


dict_object = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': {'key3a': 'value3a'},
    'key4': {
        'key4a': {
            'key4a1': 'value4a1',
            'key4a2': 'value4a2',
            'key4a3': 'value4a3'
        },
        'key4b': {
            'key4b1': {
                'key4b1a': 'value4b1a',
                'key4b1b': 'value4b1b',
                'key4b1c': 'value4b1c'
            },
            'key4c': {
                'key4c1': {
                    'key4c1a': 'value4c1a',
                    'key4c1b': 'value4c1b',
                    'key4c1c': 'value4c1c'
                }
            }
        }
    }
}

def print_dict(dictionary, path='', parent=''):
    """ This finction recursively prints nested dictionaries."""

    #Sort the dictionary object by its keys
    if isinstance(dictionary, dict):
        dictionary = collections.OrderedDict(sorted(dictionary.items()))
    else:
        dictionary = sorted(dictionary.items(), key=operator.itemgetter(1))

    #iterate each sorted dictionary key
    for key, value in dictionary.iteritems():
        if isinstance(value, dict):
            path = ''
            path = '%s/%s/%s' % (path, parent, key)

            #Repeat this funtion for nested {} instances
            print_dict(value, path, key)
        else:
            #Print the last node i.e PATH + KEY + VALUE
            print '%s/%s/%s' % (path, key, value)

if __name__ == '__main__':
    print_dict(dict_object)

1 个答案:

答案 0 :(得分:2)

您的功能显得过于复杂。只有在您拥有不是字典的对象时才会实际打印,否则会递归字典中的所有值。我将路径处理简化为一个字符串:

def print_dict(ob, path=''):
    if not isinstance(ob, dict):
        print '{}/{}'.format(path, ob)
    else:
        for key, value in sorted(ob.items()):
            print_dict(value, '{}/{}'.format(path, key))

我没有打扰创建OrderedDict个对象;您只需按排序顺序进行迭代。

这会产生预期的输出:

>>> print_dict(dict_object)
/key1/value1
/key2/value2
/key3/key3a/value3a
/key4/key4a/key4a1/value4a1
/key4/key4a/key4a2/value4a2
/key4/key4a/key4a3/value4a3
/key4/key4b/key4b1/key4b1a/value4b1a
/key4/key4b/key4b1/key4b1b/value4b1b
/key4/key4b/key4b1/key4b1c/value4b1c
/key4/key4b/key4c/key4c1/key4c1a/value4c1a
/key4/key4b/key4c/key4c1/key4c1b/value4c1b
/key4/key4b/key4c/key4c1/key4c1c/value4c1c