python 2d array to dict

末鹿安然 提交于 2019-12-06 00:14:36
>>> arr =[[0, 2, 3],
          [2, 0, 4],
          [3, 4, 0]]
>>> dict(((j,i), arr[i][j]) for i in range(len(arr)) for j in range(len(arr[0])) if i<j)
{(2, 0): 3, (1, 0): 2, (2, 1): 4}

One way to do it is with ndenumerate and defaultdict.

Building a dict mapping each value to all its positions:

>>> d = defaultdict(list)
>>> for pos,val in numpy.ndenumerate(a):
...     if val:
...         d[val].append(pos[1])
... 
>>> d
defaultdict(<class 'list'>, {2: [1, 0], 3: [2, 0], 4: [2, 1]})

And then reversing keys and values:

>>> {tuple(v):k for k,v in d.items()}
{(2, 0): 3, (1, 0): 2, (2, 1): 4}

If your python version does not support dict comprhension, this last part could be:

>>> dict((tuple(v),k) for k,v in d.iteritems())
{(2, 0): 3, (1, 0): 2, (2, 1): 4}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!