0
groups = ['A','B','C']

ranges = [1,2,3,4,5,6,7,8,9]

my_dict = {}
for g in groups:
   my_dict[g] = ???

The result (my_dict) should be as follows:

{'A': array([1, 2, 3], dtype=int64), 'B': array([4,5,6], dtype=int64)), 'C': array([7,8,9], dtype=int64)}
  • possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – Ashwini Chaudhary May 06 '14 at 07:58

2 Answers2

2

First I would turn your ranges in to properly sized chunks:

>>> ranges = zip(*[iter(ranges)]*len(groups))
>>> print(ranges)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

This will create chunks of len(groups) items which you can then feed to zip() in the second part.

Then create the dictionary, using a dictionary comprehension and zip().

>>> from numpy import array
>>> my_dict = {g: array(r) for g, r in zip(groups, ranges)}
>>> print(my_dict)
{'A': array([1, 2, 3]), 'C': array([7, 8, 9]), 'B': array([4, 5, 6])}
msvalkon
  • 11,887
  • 2
  • 42
  • 38
1
>>> import itertools
>>>
>>> groups = ['A','B','C']
>>> ranges = [1,2,3,4,5,6,7,8,9]
>>> dict(zip(groups,
...          (list(itertools.islice(it, 3)) for it in [iter(ranges)]*3)))
{'A': [1, 2, 3], 'C': [7, 8, 9], 'B': [4, 5, 6]}
falsetru
  • 357,413
  • 63
  • 732
  • 636