1

I represent a Matrix by a dictionary and assuming that I have a dictionary that the keys are the row indices, how can I convert it (in-place seems tricky) to a dictionary that the keys will be the column indices?


Here is my attempt:

by_row = {}
N = 3
M = 5
for i in range(1, N):
    row = []
    for j in range(1, M):
        row.append(j)
    by_row[i] = row
print by_row

by_column = {}
for i in range(1, M):
    col = []
    for j in range(1, N):
        col.append(by_row[j][i - 1])
    by_column[i] = col
print by_column

but I am looking for something more elegant and Pythonic. Here my_dict_1 has the row indices as keys, while my_dict_2 has the column indices as keys. Output:

{1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305

2 Answers2

3

Use the enumerate() function to number your columns, and iterate over the keys in sorted order:

by_column = {}
for rownum, row in sorted(by_row.iteritems()):
    for colnum, value in enumerate(row, 1):
        by_column.setdefault(colnum, []).append(value)

This assumes your dictionary has all row numbers present, and all rows are of equal length.

Demo:

>>> N, M = 2, 4  # 2 rows, each 4 columns
>>> by_row = {r: range(1, M + 1) for r in range(1, N + 1)}
>>> by_row
{1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
>>> by_column = {}
>>> for rownum, row in sorted(by_row.iteritems()):
...     for colnum, value in enumerate(row, 1):
...         by_column.setdefault(colnum, []).append(value)
...
>>> by_column
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Here's a super pythonic way for you:

>>> by_row = {1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
>>> by_column = {n+1:[row[n] for row in by_row.values()] for n in range(len(by_row[1]))}
>>> by_column
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
kmaork
  • 5,722
  • 2
  • 23
  • 40