-1

I have a defaultdict(list) of:

d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})

Is there a pythonic way to save each n element in each list into a new array so I have something like this?:

a = [1,6,11]
b = [2,7,12]
c = [3,8,13]
d = [4,9,14]
e = [5,10,15]
jpp
  • 159,742
  • 34
  • 281
  • 339

3 Answers3

2

The following code will calculate an array nth_el, such than nth_el[i] contains all the i-th elements:

d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})

nth_el = [[d_int[k][i] for k in range(3)] for i in range(5)]

Value of nth_el :

[[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]]
nyr1o
  • 966
  • 1
  • 9
  • 23
2

Dictionaries are not considered ordered. However, one way to get the output you desire is to construct a collections.OrderedDict of your collections.defaultdict object, then apply some zip magic:

from collections import OrderedDict, defaultdict

d_int = OrderedDict(sorted(defaultdict(list, {0: [1,2,3,4,5],
                           1: [6,7,8,9,10], 2: [11,12,13,14,15]}).items()))

dict(enumerate(zip(*d_int.values())))

# {0: (1, 6, 11), 1: (2, 7, 12), 2: (3, 8, 13), 3: (4, 9, 14), 4: (5, 10, 15)}

The benefit of this method is that you do not have to extract length of the dictionary and its constituent lists. In addition, enumerate and zip are both efficient, lazy functions.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

The example output is almost certainly impractical; if we have data of the same kind, put it in a list. Here's one crude example:

>>> d_int = defaultdict(type, {0: [1,2,3,4,5], 1: [6,7,8,9,10], 2: [11,12,13,14,15]})
>>> list(zip(*(v for k,v in sorted(d_int.items()))))
[(1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14), (5, 10, 15)]

The steps are as follows: items extracts key,value pairs from the dictionary. sorted then sorts them by key, the v for k,v in generator expression discards the keys, * distributes the values as individual arguments to zip which transposes them. Finally, list builds a list from the zip object (which is iterable).

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26