-2

How do I rearrange a dict according to a specific key value. If I have a dict:

data = {'X':[0,1,2,3], 'Frame':[0,1,2,3], 'Particle':[1,1,2,2]} 

How do I split/rearrange the dict according to the Particle value so I get:

# Arranged by particle
data1 = {'1': {'X':[0,1], 'Frame':[0,1]}, 
     '2': {'X':[2,3], 'Frame':[2,3]}}

And how could I convert back to the original.

kezzos
  • 3,023
  • 3
  • 20
  • 37

2 Answers2

1

Consider creating a class that has X, Frame, and Particle attributes. Then, instead of having a dictionary containing parallel lists, you can have a relatively simpler list of objects, which can be sorted and grouped however you like.

import itertools

class Sprocket:
    def __init__(self, x, frame, particle):
        self.x = x
        self.frame = frame
        self.particle = particle

data = [
    Sprocket(0,0,1),
    Sprocket(1,1,1),
    Sprocket(2,2,2),
    Sprocket(3,3,2),
]

#now we arrange them by particle.
arrange_func = lambda item: item.particle
data.sort(key=arrange_func)
for particle, sprockets in itertools.groupby(data, key=arrange_func):
    print "sprockets with particle {}:".format(particle)
    for sprocket in sprockets:
        print sprocket.x, sprocket.frame, sprocket.particle

Result:

sprockets with particle 1:
0 0 1
1 1 1
sprockets with particle 2:
2 2 2
3 3 2

... And if you really really want to, you can use this to construct your dictionary.

arrange_func = lambda item: item.particle
data.sort(key=arrange_func)
d = {}
for particle, sprockets in itertools.groupby(data, key=arrange_func):
    d[particle] = {"X":[], "Frame":[]}
    for sprocket in sprockets:
        d[particle]["X"].append(sprocket.x)
        d[particle]["Frame"].append(sprocket.frame)

print d

Result:

{1: {'X': [0, 1], 'Frame': [0, 1]}, 2: {'X': [2, 3], 'Frame': [2, 3]}}
Kevin
  • 74,910
  • 12
  • 133
  • 166
0

@Kevin thanks for your answer, but I found a solution with pandas:

import pandas as pd

data = {'X':[0,1,2,3], 'Frame':[0,1,2,3], 'Particle':[2,2,4,5]} 

print data, '\n'

df = pd.DataFrame(data)
grouped = df.groupby(['Particle'])
d = {}
for name, group in grouped:
    d[name] = group.to_dict('list')

print d, '\n'

# For the return journey:
pieces = []
for key, value in d.iteritems():
    pieces.append(pd.DataFrame(value))
concatenated = pd.concat(pieces)
print concatenated.to_dict('list')

Out put is:

{'X': [0, 1, 2, 3], 'Frame': [0, 1, 2, 3], 'Particle': [2, 2, 4, 5]} 

{2: {'X': [0, 1], 'Frame': [0, 1], 'Particle': [2, 2]}, 4: {'X': [2], 'Frame': [2], 'Particle': [4]}, 5: {'X': [3], 'Frame': [3], 'Particle': [5]}} 

{'X': [0, 1, 2, 3], 'Frame': [0, 1, 2, 3], 'Particle': [2, 2, 4, 5]}
kezzos
  • 3,023
  • 3
  • 20
  • 37