Convert list of tuples into a dictionary with list of tuples

Question:

Input:

original_list = [(5, 10, 8, 2, 3, 12, 'first', 'second', 2, 80, 75, 'third'), (8, 2, 8, 14, 7, 3, 'name', 'last', 2, 80, 75, 'block')]

Output:

new = {'specs':[(5, 10, 8, 2, 3, 12), (8, 2, 8, 14, 7, 3)], 'data': [('first', 'second', 2, 80, 75, 'third'), ('name', 'last', 2, 80, 75, 'block')]}

I need to separate the list of tuples (might be more than two shown above) into a dictionary with two keys: ‘specs’ and ‘data’

‘specs’ values are supposed to be a list of tuples having first 6 elements from each tuple from original_list.

‘data’ values are supposed to be a list of tuples having all the other elements from original_list.

Asked By: thisisjustme

||

Answers:

A couple of list comprehensions and Bob’s your uncle:

original_list = [
    (5, 10, 8, 2, 3, 12, "first", "second", 2, 80, 75, "third"),
    (8, 2, 8, 14, 7, 3, "name", "last", 2, 80, 75, "block"),
]
new = {
    "specs": [tuple(l[:6]) for l in original_list],
    "data": [tuple(l[6:]) for l in original_list],
}
print(new)

outputs

{
  'specs': [(5, 10, 8, 2, 3, 12), (8, 2, 8, 14, 7, 3)], 
  'data': [('first', 'second', 2, 80, 75, 'third'), ('name', 'last', 2, 80, 75, 'block')]
}
Answered By: AKX
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.