Search code examples
pythonjsonlistdictionarytuples

Merge list of tuples to a dictionary


I have following list of tuples

[
('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')
]

and I want to create following dictionary of dictionaries:

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

What is the best option? I have to extract data from a bbdd and generate a JSON file so this conversion will be done many times and it is needed the most efficient solution


Solution

  • I just hacked a solution for you:

    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)