matteo - 1 year ago 129
Python Question

# Python filter dictionary unique values in a key and create another filtered dictionary

the question is trivial but I'm not able to do it.

I have this initial dictionary:

``````d = {'res': [1.1, 2.2, 1.2, 4.5, 1.5, 3.4], 'sp': [1, 1, 2, 3, 4, 4], 'obs': [1, 2, 3, 4, 5, 6]}
``````

I would like to take each value of the
`sp`
key and transform it in the key of a new dictionary where, for each unique value I have another dictionary with the coherent other key values.

The final output should explain much better the problem:

``````new_dict = {1: {'res': [1.1, 2.2], 'obs': [1, 2]}, 2: {'res': [1.2], 'obs': [3]}, 3: {'res': [4.5], 'obs': [4]}, 4: {'res': [1.5, 3.4], 'obs': [5, 6]}}
``````

so the keys of this dictionary are the unique values of the
`sp`
key of the original dictionary.

Thanks guys

``````d = {'res': [1.1, 2.2, 1.2, 4.5, 1.5, 3.4], 'sp': [1, 1, 2, 3, 4, 4], 'obs': [1, 2, 3, 4, 5, 6]}
``````

Given that input:

``````r = {}
for i, v in enumerate(d['sp']):
r.setdefault(v, {'res':[],'obs':[]})
r[v]['res'].append(d['res'][i])
r[v]['obs'].append(d['obs'][i])
``````

This results in:

``````>>> r
{1: {'res': [1.1, 2.2], 'obs': [1, 2]}, 2: {'res': [1.2], 'obs': [3]}, 3: {'res': [4.5], 'obs': [4]}, 4: {'res': [1.5, 3.4], 'obs': [5, 6]}}
``````

This could also be written as:

``````from itertools import izip, groupby
r = dict((k[0], {'obs':list(o), 'res':list(r)})
for k, o, r in (zip(*g[1]) for g in
groupby(izip(d['sp'],d['obs'],d['res']), key=lambda v: v[0])))
``````

Which results in the same result. But I have not compared it for cost.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download