Skip to content Skip to sidebar Skip to footer

Create Dict Using A Grouping Column In An Array And Assigning The Remaining Columns To Values Of The Dict

I have a type(s1) = numpy.ndarray. I want to create a dictionary by using the first column of s1 as key and rest as values to the key. The first column has repeated values. Here i

Solution 1:

You can simply built them with defaultdict :

d=collections.defaultdict(list)
for k,*v in s1 : d[k].append(list(v))

for

defaultdict(list,
            {1: [['R', 4], ['D', 3], ['I', 10], ['K', 0.0]],
             2: [['R', 11], ['D', 13], ['I', 1], ['K', 6]],
             3: [['R', 12], ['D', 17], ['I', 23], ['K', 10]]}) 

EDIT

You can nest dicts in dicts :

d=collections.defaultdict(dict)
for k1,k2,v in s1 : d[k1][k2]=v 

#defaultdict(dict,#       {1: {'D': 3, 'I': 10, 'K': 0.0, 'R': 4},#        2: {'D': 13, 'I': 1, 'K': 6, 'R': 11},#        3: {'D': 17, 'I': 23, 'K': 10, 'R': 12}})

In [67]: d[2]['K']
Out[67]: 6

See here for generalization.

Solution 2:

You might want to use itertools.groupby():

In [15]: {k: [list(x[1:]) for x in g]
   ....:  for k,g in itertools.groupby(s1, key=lambda x: x[0])}
Out[15]: 
{1L: [['R', 4], ['D', 3], ['I', 10], ['K', 0.0]],
 2L: [['R', 11], ['D', 13], ['I', 1], ['K', 6]],
 3L: [['R', 12], ['D', 17], ['I', 23], ['K', 10]]}

Post a Comment for "Create Dict Using A Grouping Column In An Array And Assigning The Remaining Columns To Values Of The Dict"