Search code examples
pythonnumpydictionarycollectionsdefaultdict

Getting the n element of each list in a defaultdict


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]

Solution

  • 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.