user3235542
user3235542

Reputation:

simple dictionary manipulation in python

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)}

Upvotes: 0

Views: 46

Answers (2)

msvalkon
msvalkon

Reputation: 12077

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])}

Upvotes: 2

falsetru
falsetru

Reputation: 369054

>>> 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]}

Upvotes: 1

Related Questions