Splitting dict by value of one of the keys

后端 未结 4 823
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 19:45

I\'ve got a dictionary with data of the same length (but different types), something like:

data = {
    \"id\": [1,1,2,2,1,2,1,2], 
    \"info\": [\"info1\",         


        
4条回答
  •  死守一世寂寞
    2020-12-19 20:12

    For working with records, I personally like numpy.recarray.

    In [3]: import numpy as np
    In [4]: fields = data.keys()
    In [8]: recs = zip(*[ lst for k, lst in data.iteritems() ])
    
    In [9]: recs[0]
    Out[9]: ('info1', 1, 1)
    In [10]: recs[1]
    Out[10]: ('info2', 1, 2)
    
    In [21]: ra = np.rec.fromrecords(recs, names = fields )
    In [17]: ra
    rec.array([('info1', 1, 1), ('info2', 1, 2), ('info3', 2, 3), ('info4', 2, 4),
           ('info5', 1, 5), ('info6', 2, 6), ('info7', 1, 7), ('info8', 2, 8)], 
          dtype=[('info', 'S5'), ('id', '

    If you want to group the records by id in a dict, do:

    { id: ra[ra.id == id] for id in set(ra.id) }
    

提交回复
热议问题