Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert list of tuples into a dictionary with list of tuples

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

‘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.

>Solution :

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')]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading