Search code examples
pythonlistdictionarypython-2.7ordereddictionary

How to make ordered dictionary from list of lists?


The problem is: Having a list of names, and a list of lists, how to create a list, in which each item is an ordered dictionary with names as keys, and items from list of lists as values? It might be more clear from code below:

from collections import OrderedDict

list_of_lists = [
                ['20010103', '0.9507', '0.9569', '0.9262', '0.9271'],
                ['20010104', '0.9271', '0.9515', '0.9269', '0.9507'],
                ['20010105', '0.9507', '0.9591', '0.9464', '0.9575'],
                ]

names = ['date', 'open', 'high', 'low', 'close']

I would like to get:

ordered_dictionary = [
                     OrderedDict([('date', '20010103'), ('open', '0.9507'), ('high', '0.9569'), ('low', '0.9262'), ('close', '0.9271')]),
                     OrderedDict([('date', '20010104'), ('open', '0.9271'), ('high', '0.9515'), ('low', '0.9269'), ('close', '0.9507')]),
                     OrderedDict([('date', '20010105'), ('open', '0.9507'), ('high', '0.9591'), ('low', '0.9464'), ('close', '0.9575')]),
                     ]

Solution

  • Use zip() to combine the names and the values. With a list comprehension:

    from collections import OrderedDict
    
    ordered_dictionary = [OrderedDict(zip(names, subl)) for subl in list_of_lists]
    

    which gives:

    >>> from pprint import pprint
    >>> pprint([OrderedDict(zip(names, subl)) for subl in list_of_lists])
    [OrderedDict([('date', '20010103'), ('open', '0.9507'), ('high', '0.9569'), ('low', '0.9262'), ('close', '0.9271')]),
     OrderedDict([('date', '20010104'), ('open', '0.9271'), ('high', '0.9515'), ('low', '0.9269'), ('close', '0.9507')]),
     OrderedDict([('date', '20010105'), ('open', '0.9507'), ('high', '0.9591'), ('low', '0.9464'), ('close', '0.9575')])]