0

I have a dictionary of lists, where the lists represent columns. All the lists are the same length and the number of lists is variable. I want to convert the lists of columns into lists of rows. It doesn't have to end in a dictionary a matrix is perfect; however, I can't use numpy.

For example: The setup looks something like this

>>> A = [ 1 ,  2 ,  3 ,  4 ,  5 ,  6]
>>> B = ["A", "B", "C", "D", "E", "F"]
>>> C = ["J", "K", "L", "M", "N", "O"]
>>> d = {"One": A, "Two": B, "Three": C}

do magic here and get the following

[(1, 'A', 'J'), (2, 'B', 'K'), (3, 'C', 'L'), (4, 'D', 'M'), (5, 'E', 'N'), (6, 'F', 'O')]

Notice the first element in the cols are now in a row. Now I can get this by doing

>>> zip(d["One"], d["Two"], d["Three"])

but this would only work if the number of dictionary entries was constant. How can I do this if the number of dictionary entries was variable? Hope I'm clear.

Jeff
  • 6,932
  • 7
  • 42
  • 72
  • Does the order of the keys in the dictionary matter? I mean, are the keys really `"One"`, `"Two"`, `"Three"`, and you want to use them in the usual order? – Sven Marnach Feb 07 '12 at 17:37
  • @Sven Marnach No order does not matter. – Jeff Feb 07 '12 at 17:38
  • possible duplicate of [A Transpose/Unzip Function in Python](http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python) – Paolo Moretti Feb 07 '12 at 17:39

2 Answers2

4

If the order of the dictionary items does not matter, you can do

zip(*d.values())

to get the desired result.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
2

Check out the documentation for Unpacking Argument Lists. By putting a * in front of an iterable that is an argument to a function, the function will be called with the elements from that iterable as its arguments. For example zip(*['ab', 'cd', 'ef']) would become zip('ab', 'cd', 'ef').

Using this method you can generate your zipped list of an arbitrarily sized dictionary, but note that because dictionaries are unordered you will need to provide a separate list to use as an order for the resulting column groups, for example:

>>> A = [ 1 ,  2 ,  3 ,  4 ,  5 ,  6]
>>> B = ["A", "B", "C", "D", "E", "F"]
>>> C = ["J", "K", "L", "M", "N", "O"]
>>> d = {"One": A, "Two": B, "Three": C}
>>> order = ["One", "Two", "Three"]
>>> zip(*[d[k] for k in order])
[(1, 'A', 'J'), (2, 'B', 'K'), (3, 'C', 'L'), (4, 'D', 'M'), (5, 'E', 'N'), (6, 'F', 'O')]

If the column order does not matter, you can use Sven's solution which is very concise but the tuple order will be arbitrary.

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306