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

Create nested list from list in python

Need to get nested lists from the list in python

list_values=[('BNB', '161221'),
 ('BNB', '171221'),
 ('BNB', '241221'),
 ('BNB', '280122'),
 ('BNB', '311221'),
 ('BTC', '161221'),
 ('BTC', '171221'),
 ('BTC', '241221'),
 ('BTC', '250222'),
 ('BTC', '250322'),
 ('BTC', '280122'),
 ('BTC', '311221')]

The output of lists needed is

List_op=[[('BNB', '161221'),
 ('BNB', '171221'),
 ('BNB', '241221'),
 ('BNB', '280122'),
 ('BNB', '311221')],
[('BTC', '161221'),
 ('BTC', '171221'),
 ('BTC', '241221'),
 ('BTC', '250222'),
 ('BTC', '250322'),
 ('BTC', '280122'),
 ('BTC', '311221')]]

I have tried with some list comprehension methods, but couldnt get this. Help is appreciated.

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

>Solution :

A simple solution:

from collections import defaultdict

list_values = [
    ('BNB', '161221'),
    ('BNB', '171221'),
    ('BNB', '241221'),
    ('BNB', '280122'),
    ('BNB', '311221'),
    ('BTC', '161221'),
    ('BTC', '171221'),
    ('BTC', '241221'),
    ('BTC', '250222'),
    ('BTC', '250322'),
    ('BTC', '280122'),
    ('BTC', '311221')
]

# a dict might be a better data type here
result = defaultdict(list)
for k, v in list_values:
    result[k].append(v)
print(result)

# but if you need a list of lists instead of a dictionary:
result = defaultdict(list)
for k, v in list_values:
    result[k].append((k, v))
list_op = [*result.values()]
print(list_op)

Output:

defaultdict(<class 'list'>, {'BNB': ['161221', '171221', '241221', '280122', '311221'], 'BTC': ['161221', '171221', '241221', '250222', '250322', '280122', '311221']})
[[('BNB', '161221'), ('BNB', '171221'), ('BNB', '241221'), ('BNB', '280122'), ('BNB', '311221')], [('BTC', '161221'), ('BTC', '171221'), ('BTC', '241221'), ('BTC', '250222'), ('BTC', '250322'), ('BTC', '280122'), ('BTC', '311221')]]
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