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']]
Related posts
- How to sort a list of dicts in Python — posted 2010-04-02
- Python setdefault example — posted 2010-02-09
- How to conditionally replace items in a list — posted 2008-08-22
- How to use Python's enumerate and zip to iterate over two lists and their indices. — posted 2008-04-18
- How to invert a dict in Python — posted 2008-01-14
- How to find the intersection and union of two lists in Python — posted 2008-01-03
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(5)
-
aws
(9)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(13)
-
conkeror
(2)
-
core
(2)
-
cygwin
(17)
-
datastructures
(14)
-
datetime
(4)
-
decorators
(4)
-
django
(40)
-
emacs
(22)
-
files_directories
(11)
-
git
(5)
-
hardware
(5)
-
install_setup
(8)
-
javascript
(3)
-
keyboard
(9)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
persistence
(5)
-
preferences
(7)
-
processes
(4)
-
pyqt
(18)
-
python
(144)
-
ratpoison
(3)
-
regexes
(6)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(14)
-
ssh
(10)
-
subversion
(6)
-
twisted
(7)
-
ubuntu
(65)
-
urxvt
(5)
-
vxworks
(25)
-
webdev
(5)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Marty Alchin
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan