Python多级dict到字符串

时间:2015-02-05 15:47:48

标签: python string dictionary

我有一个python字典和一些带有某些值的字典。我正在尝试生成结构中键的带点分隔的字符串,其末尾的值。通过下面的例子,我想要FIELD0 1和NAME。我可以创建一个for循环来处理数据或递归函数。我不知道是否有一些预先构建的方法可以将多级字典折叠为分隔字符串?

我正在尝试以下内容,但正如您所知,它只会附加子词典。

'.'.join('%s %s\n' % i for i in a.items())

{'BOGUS1': 'BOGUS_VAL1',
 'BOGUS2': 'BOGUS_VAL1',
 'FIELD0': {'F0_VAL1': 1, 'F0_VAL2': 2},
 'FIELD1': {'F1_VAL1': 80, 'F1_VAL2': 67, 'F1_VAL3': 100},
 'FOOBAR1': 'FB_VAL1',
 'NAME': 'VALUE'}

BOGUS2.BOGUS_VAL1
.NAME.VALUE
.BOGUS1.BOGUS_VAL1
.FIELD0.{'F0_VAL1': 1, 'F0_VAL2': 2}
.FIELD1.{'F1_VAL2': 67, 'F1_VAL3': 100, 'F1_VAL1': 80}
.FOOBAR1.FB_VAL1

# Wanted results
FIELD0.F0_VAL1 1
FIELD0.F0_VAL2 2
FIELD1.F1_VAL1 80
FIELD1.F2_VAL1 67
FIELD1.F3_VAL1 100
NAME VALUE

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

def dotnotation(d, prefix = ''):
    for k, v in d.items():
        if type(v) == type(dict()):
            dotnotation(v, prefix + str(k) + '.')
        else:
            print prefix + str(k) + ' = ' + str(v)

还可以根据存储的类型更改格式。这应该适用于您的示例。

答案 1 :(得分:1)

这是我的方法:

def dotted_keys(dic):
    """ Generated dot notation keys from a dictionary """
    queue = [(None, dic)]  # A queue of (prefix, object)
    while queue:
        prefix, current = queue.pop(0)
        for k, v in current.iteritems():
            if isinstance(v, dict):
                queue.append((k, v))
            elif prefix:
                yield prefix + '.' + k
            else:
                yield k


def dict_search(dic, dotted_key, default=None):
    """ Take a dictionary and a dotted key and return the value. If not
    found, return the value specified by the default parameter.

    Example: dict_search(d, 'FIELD0.F0_VAL2')
    """
    current = dic
    keys = dotted_key.split('.')

    for k in keys:
        if k in current:
            current = current[k]
        else:
            return default
    return current


if __name__ == '__main__':
    d = {
        'BOGUS1': 'BOGUS_VAL1',
        'BOGUS2': 'BOGUS_VAL1',
        'FIELD0': {'F0_VAL1': 1, 'F0_VAL2': 2, 'XYZ': {'X1': 9}},
        'FIELD1': {'F1_VAL1': 80, 'F1_VAL2': 67, 'F1_VAL3': 100},
        'FOOBAR1': 'FB_VAL1',
        'NAME': 'VALUE'
    }

    for k in dotted_keys(d):
        print(k, '=', dict_search(d, k))

输出:

BOGUS2 = BOGUS_VAL1
NAME = VALUE
BOGUS1 = BOGUS_VAL1
FOOBAR1 = FB_VAL1
FIELD0.F0_VAL1 = 1
FIELD0.F0_VAL2 = 2
FIELD1.F1_VAL2 = 67
FIELD1.F1_VAL3 = 100
FIELD1.F1_VAL1 = 80
XYZ.X1 = None

dotted_keys函数以点分表示法生成键列表,而dict_search函数使用虚线键并返回值。