平面嵌套字典,其中新键将是所有嵌套键的元组

时间:2019-04-19 18:21:16

标签: python python-3.x

我有一个这样的字典:

previous_dict = {
    'dict_1': 'dict_1',
    'dict_2': {
        'dict_2_1': 'dict_2_1',
        'dict_2_2': 'dict_2_2'
    },
    'dict_3': 3,
    'dict_4': None,
    'dict_5': dict()
}

我编写了一个函数,将所有键作为元组平整字典,输出为:

previously_expected_dict = {}
for key, value in previous_dict.items():
    if type(value) == dict:
        for k, v in value.items():
            previously_expected_dict[(key, k)] = v
    else:
        previously_expected_dict[(key,)] = value

输出:

print(previously_expected_dict)
{
    ('dict_1',): 'dict_1',
    ('dict_2', 'dict_2_1'): 'dict_2_1',
    ('dict_2', 'dict_2_2'): 'dict_2_2',
    ('dict_3',): 3,
    ('dict_4',): None
}
  

dict_5因为没有任何值而被丢弃


现在需求已更改,并且字典可以具有任意数量的嵌套

new_dict = {
    'dict_1': {
        'dict_1_1': {
            'dict_1_1_1': 'dict_1_1_1',
            'dict_1_1_2': 'dict_1_1_2'
        }
    },
    'dict_2': {
        'dict_2_1': 'dict_2_1',
        'dict_2_2': 'dict_2_2'
    },
    'dict_3': 'dict_3',
    'dict_4': dict()
}

到目前为止我尝试过的代码

def make_flat(my_dict):
    nd = dict()
    keys = []

    def loop_me(value):
        nonlocal keys
        if isinstance(value, dict):
            for k, v in value.items():
                keys.append(k)
                loop_me(v)
        else:
            nd[tuple(keys)] = value
            keys.pop(-1)

    loop_me(my_dict)
    return nd


print(make_flat(new_dict))

但是我在元组中收到了额外的密钥

{
    ('dict_1', 'dict_1_1', 'dict_1_1_1'): 'dict_1_1_1',  # Perfect
    ('dict_1', 'dict_1_1', 'dict_1_1_2'): 'dict_1_1_2',  # Perfect
    ('dict_1', 'dict_1_1', 'dict_2', 'dict_2_1'): 'dict_2_1',  # Error, Expected is: ('dict_2', 'dict_2_1')
    ('dict_1', 'dict_1_1', 'dict_2', 'dict_2_2'): 'dict_2_2',  # Error, Expected is: ('dict_2', 'dict_2_2')
    ('dict_1', 'dict_1_1', 'dict_2', 'dict_3'): 'dict_3'  # Error, Expected is: ('dict_3',)
}

最终预期输出:

output = {
    ('dict_1', 'dict_1_1', 'dict_1_1_1'): 'dict_1_1_1',
    ('dict_1', 'dict_1_1', 'dict_1_1_2'): 'dict_1_1_2',
    ('dict_2', 'dict_2_1'): 'dict_2_1',
    ('dict_2', 'dict_2_2'): 'dict_2_2',
    ('dict_3',): 'dict_3'
}

我尝试使用for循环和递归函数Failed。

3 个答案:

答案 0 :(得分:2)

您可以使用递归:

def flatten(d, c = []):
  for a, b in d.items():
    if not isinstance(b, dict):
       yield (tuple(c+[a]), b)
    else:
       yield from flatten(b, c+[a])

print(dict(flatten(previous_dict)))

输出:

{('dict_1',): 'dict_1', ('dict_2', 'dict_2_1'): 'dict_2_1', ('dict_2', 'dict_2_2'): 'dict_2_2', ('dict_3',): 3, ('dict_4',): None}

使用new_dict

{('dict_1', 'dict_1_1', 'dict_1_1_1'): 'dict_1_1_1', ('dict_1', 'dict_1_1', 'dict_1_1_2'): 'dict_1_1_2', ('dict_2', 'dict_2_1'): 'dict_2_1', ('dict_2', 'dict_2_2'): 'dict_2_2', ('dict_3',): 'dict_3'}

答案 1 :(得分:2)

您可以使用一个函数来遍历字典项,然后将键添加到递归调用返回的子键元组中:

Map(function(x, y) subset(x, boolean == y), x = dataframes, y = names(dataframes))
#$yes
#  numbers boolean
#1       3     yes
#2       4     yes
#3       7     yes
#4       8     yes
#5      10     yes

#$no
#  letters numbers boolean
#1       Y       5      no
#2       F       6      no
#3       P       4      no
#4       C       2      no
#5       Z      10      no
#6       I       8      no
#7       X       7      no
#8       V       3      no

使def flatten(d): for k, v in d.items(): if isinstance(v, dict): for s, i in flatten(v): yield (k, *s), i else: yield (k,), v 返回:

dict(flatten(new_dict))

答案 2 :(得分:1)

我已经使用deep变量来确定和更正键,并且make_flat函数返回了所需的输出,但是,@ Ajax1234更加清晰了。

def make_flat(dict_):
    new_dict = dict()
    keys = []

    def loop_recursively(value, deep=0):
        nonlocal keys
        if isinstance(value, dict):
            deep += 1
            for k, v in value.items():
                keys.append(k)
                loop_recursively(v, deep)
            else:
                deep -= 1
        else:
            keys = keys[-deep:]
            new_dict[tuple(keys)] = value
            keys.pop(-1)

    loop_recursively(dict_)
    return new_dict