Matrix as a dictionary; is it safe?

不问归期 提交于 2019-12-13 08:06:39

问题


I know that the order of the keys is not guaranteed and that's OK, but what exactly does it mean that the order of the values is not guaranteed as well*?

For example, I am representing a matrix as a dictionary, like this:

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

Are the columns of my matrix correctly constructed? Let's say I have 3 rows and at this signatures_dict[i] = row line, row will always have 1, 2, 3, 4, 5. What will signatures_dict be?

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

or something like

1 2 3 4 5
1 4 3 2 5
5 1 3 4 2

? I am worried about cross-platform support.

In my application, the rows are words and the columns documents, so can I say that the first column is the first document?

*Are order of keys() and values() in python dictionary guaranteed to be the same?


回答1:


You will guaranteed have 1 2 3 4 5 in each row. It will not reorder them. The lack of ordering of values() refers to the fact that if you call signatures_dict.values() the values could come out in any order. But the values are the rows, not the elements of each row. Each row is a list, and lists maintain their order.

If you want a dict which maintains order, Python has that too: https://docs.python.org/2/library/collections.html#collections.OrderedDict




回答2:


Why not use a list of lists as your matrix? It would have whatever order you gave it;

In [1]: matrix = [[i for i in range(4)] for _ in range(4)]

In [2]: matrix
Out[2]: [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

In [3]: matrix[0][0]
Out[3]: 0

In [4]: matrix[3][2]
Out[4]: 2


来源:https://stackoverflow.com/questions/37090291/matrix-as-a-dictionary-is-it-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!