Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

python - 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 is np.array.

s1 = np.array([[1L, 'R', 4],
       [1L, 'D', 3],
       [1L, 'I', 10],
       [1L, 'K', 0.0],
       [2L, 'R', 11],
       [2L, 'D', 13],
       [2L, 'I', 1],
       [2L, 'K', 6],
       [3L, 'R', 12],
       [3L, 'D', 17],
       [3L, 'I', 23],
       [3L, 'K', 10]], dtype=object)

I want to get the following:

{'1':[['R',4],['D',3],['I',10],['K',0]],
  '2':[['R',11],['D',13],['I',1],['K',6]],
  '3':[['R',12],['D',17],['I',23],['K',10]]}

This is what I tried and got:

In [18]: {x[0]:[x[1],x[2]] for x in s1}
Out[18]: {1L: ['K', 0.0], 2L: ['D', 6], 3L: ['K', 10]}

I see the problem that the grouping column has repeated values. But I am unable to do the appending. What is the trick I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...