如何按价值安排一个字典,然后再回来?

时间:2014-11-19 18:02:16

标签: python dictionary

如何根据特定键值重新排列dict。如果我有一个词典:

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

如何根据粒子值拆分/重新排列dict,以便我得到:

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

我怎样才能转换回原版。

2 个答案:

答案 0 :(得分:1)

考虑创建一个具有X,Frame和Particle属性的类。然后,您可以拥有一个相对简单的对象列表,而不是包含并行列表的字典,您可以按照自己的喜好对其进行排序和分组。

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

结果:

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

...如果你真的想要,你可以用它来构建你的字典。

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

结果:

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

答案 1 :(得分:0)

@Kevin感谢您的回答,但我找到了一个大熊猫的解决方案:

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是:

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