将元组列表合并到字典

2024-10-06 12:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的元组列表

[
('A-1', 'B-1', 'C'), 
('A-1', 'B-2', 'D'), 
('A-1', 'B-3', 'E'), 
('A-1', 'B-4', 'F'), 
('A-1', 'B-5', 'G')
]

我想创建以下词典:

{A:{"A-1":{"B":{"B-1":"C","B-2":"D","B-3":"E","B-4":"F","B-5":"G"}}}}

最好的选择是什么?我必须从bbdd中提取数据并生成一个JSON文件,所以这种转换将被多次执行,这是最有效的解决方案


Tags: 文件数据json列表解决方案词典元组bbdd
1条回答
网友
1楼 · 发布于 2024-10-06 12:37:10

你需要学会如何提问。 你应该向我们展示你的尝试和你的所作所为。 你应该试着自己写算法。。。你知道吗

对你来说很幸运,我在工作,所以我为你破解了一个解决方案。。 试试看是否有效:

def convert_function(input):
    output = {}
    for val in input:
        first_dict = output.get(val[0][0], {})
        second_dict = first_dict.get(val[0], {})
        third_dict = second_dict.get(val[1][0], {})

        third_dict[val[1]] = val[2]
        second_dict[val[1][0]] = third_dict
        first_dict[val[0]] = second_dict

        output[val[0][0]] = first_dict
    return output

input = [
    ('A-1', 'B-1', 'C'), 
    ('A-1', 'B-2', 'D'), 
    ('A-1', 'B-3', 'E'), 
    ('A-1', 'B-4', 'F'), 
    ('A-1', 'B-5', 'G')
]

print convert_function(input)

祝你下次好运!你知道吗

相关问题 更多 >