Sriram
Sriram

Reputation: 169

Convert a list and list of tuples to dictionary

I have a list of tuples

data = [('2015-10-08', '2016-07-17'), ('Alex', 'Jerry'), (5, 6)]

And I have a list, this list contains column headings. title = [Date , Name, Age] With this list and list of tuples I want a dictionary of dictionaries

This is the expected output

output = {'1' : {'Date': '2015-10-08', 'Name': 'Alex', 'Age': 5},
          '2' : {'Date': '2016-07-17', 'Name': 'Jerry', 'Age': 6}}

I tried

output = {}
for i in range(len(title)):
    output[i+1] = {title[i]: ",".join(data[i])}

print (output)

I am getting

{1: {'Date': '2015-10-08','2016-07-17'}, 2: {'Name': 'Alex','Jerry'}, 3: {'Age': 5,6}}

Upvotes: 0

Views: 38

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149185

You could simply use loops to build easy to read code. But the Pythonic way would be to use comprehensions:

result = {str(i + 1): {t: data[j][i] for j, t in enumerate(title)}
          for i in range(len(data[0]))}

It gives as expected:

{'1': {'Age': 5, 'Date': '2015-10-08', 'Name': 'Alex'},
 '2': {'Age': 6, 'Date': '2016-07-17', 'Name': 'Jerry'}}

Upvotes: 1

Related Questions