嵌套字典转换为嵌套元组。

3
我知道这个问题本应该不难解决,但我却无法解决它。
我有一个嵌套字典,我需要将其值转换为相同结构的元组。
dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}}

结果应该是这样的:
list1 = (32, 7, ((600, 500)))

你有任何关于如何做到这一点的建议吗?

谢谢!

2个回答

1
您可以编写一个递归函数。
dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}}

def dfs_dct(dct):
    tpl = ()
    for k,v in dct.items():
        if isinstance(v, dict):
            tpl += (dfs_dct(v),)
        else:
            tpl += (v,)
    return tpl
res = dfs_dct(dict1)
print(res)

输出:

(32, 7, ((600, 500),))

1

尝试:

dict1 = {"234": 32, "345": 7, "123": {"asd": {"pert": 600, "sad": 500}}}


def get_values(o):
    out = []
    for k, v in o.items():
        if not isinstance(v, dict):
            out.append(v)
        else:
            out.append(get_values(v))
    return tuple(out)


print(get_values(dict1))

输出:

(32, 7, ((600, 500),))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接