SaltyCrane Blog — Notes on JavaScript and web development

How to convert a dictionary of lists to a list of lists in Python

UPDATE: See my new post, Tabular data structure conversion in Python for an updated method which handles non-rectangular data.

The functions below convert a rectangular dictionary of lists to a list of lists. Each list in the dictionary must be the same length. Additionally, a list of keys is required as an input argument to specify the desired ordering of the columns in the returned list of lists. If this were not specified, the order of the columns would be unknown since items in a dictionary are unordered.

The converted list of lists can contain either a list of rows or a list of columns. The first two functions create a lists of rows; the last two create a list of columns. (I consider each list in the dict of lists as a column, and all items for a given index a row.)

I also compare the imperative/procedural approach to the declarative/functional approach. I like the declarative/functional approach because it is so concise, and, I believe, a little faster as well.

#!/usr/bin/python

# IMPERATIVE/PROCEDURAL APPROACH
def byrow_imper(dol, keylist):
    """Converts a dictionary of lists to a list of lists using the
    values of the dictionaries. Each list must be the same length.
       dol: dictionary of lists
       keylist: list of keys, ordered as desired
       Returns: a list of lists where the inner lists are rows. 
         i.e. returns a list of rows. """
    lol = []
    for i in xrange(len(dol[keylist[0]])):
        row = []
        for key in keylist:
            row.append(dol[key][i])
        lol.append(row)
    return lol

# DECLARATIVE/FUNCTIONAL APPROACH
def byrow_decl(dol, keylist):
    """Converts a dictionary of lists to a list of lists using the
    values of the dictionaries. Each list must be the same length.
       dol: dictionary of lists
       keylist: list of keys, ordered as desired
       Returns: a list of lists where the inner lists are rows. 
         i.e. returns a list of rows. """
    return [[dol[key][i] for key in keylist] 
            for i in xrange(len(dol[keylist[0]]))]

# IMPERATIVE/PROCEDURAL APPROACH
def bycol_imper(dol, keylist):
    """Converts a dictionary of lists to a list of lists using the
    values of the dictionaries. Each list must be the same length.
       dol: dictionary of lists
       keylist: list of keys, ordered as desired
       Returns: a list of lists where the inner lists are columns. 
         i.e. returns a list of columns. """
    lol = []
    for key in keylist:
        col = []
        for item in dol[key]:
            col.append(item)
        lol.append(col)
    return lol

# DECLARATIVE/FUNCTIONAL APPROACH
def bycol_decl(dol, keylist):
    """Converts a dictionary of lists to a list of lists using the
    values of the dictionaries. Each list must be the same length.
       dol: dictionary of lists
       keylist: list of keys, ordered as desired
       Returns: a list of lists where the inner lists are columns. 
         i.e. returns a list of columns. """
    return [[item for item in dol[key]] for key in keylist]

# TEST
if __name__ == "__main__": 
    dol = {
        'a': ['a1', 'a2', 'a3'],   # column a
        'b': ['b1', 'b2', 'b3'],   # column b
        'c': ['c1', 'c2', 'c3'],   # column c
        }
    keylist = ['a', 'b', 'c']
    print byrow_imper(dol, keylist)
    print byrow_decl(dol, keylist)
    print bycol_imper(dol, keylist)
    print bycol_decl(dol, keylist)

Results:
[['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']]
[['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']]
[['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]
[['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']]

Comments