Home > Enterprise >  Concatenate all 2 dimensional values in a dictionary. (Output is Torch tensor)
Concatenate all 2 dimensional values in a dictionary. (Output is Torch tensor)

Time:12-03

I want to concatenate all 2 dimensional values in a dictionary.

The number of rows of these values is always the same.

D = {'a': [[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]],
     'b': [[1, 1],
           [1, 1],
           [1, 1]]
     'c': [[2, 2, 2, 2],
           [2, 2, 2, 2],
           [2, 2, 2, 2]]
}

And the output must be form of a torch tensor.

tensor([[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]])

Any help would be appreciated!!

CodePudding user response:

from itertools import chain    
l = []
for i in range(len(D)):
    t = [ D[k][i] for k in D ] 
    l.append( list(chain.from_iterable(t)) )

Output:

[[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
 [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
 [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]]

CodePudding user response:

import torch
names = ['a', 'b', 'c']
print(torch.cat(tuple([torch.tensor(D[name]) for name in names]), dim=1))

Output:

tensor([[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]])
  • Related