I receive a dictionary with two keys, that has lists of lists as values. Example:
dict = {'points' : [[2,1],[3,4], [5,6],[7,8]], 'ids':[[2], [1], [3], [0]]}
Each point has an id associated with it, ex: point [2,1] has id[2], point[3,4] has id[1] etc .
I need to sort the points in respect to each id. So the ouput I need is something like this
dict = {'points' : [[7,8],[3,4], [2,1],[5,6]], 'ids':[[0], [1], [2], [3]]}
How can I do this?
Thanks.
CodePudding user response:
Try this:
d['ids'], d['points'] = map(list, zip(*sorted(zip(d['ids'], d['points']))))
Please don't use built in function names (such as dict) to name your variables. here I used d instead.
As suggested by Kelly in the comments below, this is also an option:
d['ids'][:], d['points'][:] = zip(*sorted(zip(d['ids'], d['points'])))
CodePudding user response:
Please don't use builtin names as variable names!
data = {'points' : [[2,1],[3,4], [5,6],[7,8]], 'ids':[[2], [1], [3], [0]]}
ids, points = zip(*sorted(zip(data['ids'], data['points'])))
print({
'points': list(points),
'ids': list(ids),
})
# output: {'points': [[7, 8], [3, 4], [2, 1], [5, 6]], 'ids': [[0], [1], [2], [3]]}
First you create zip object - it represents 'pairs' (or n-tuples if more arguments are given) of objects, so each point is bound to id. Then sorted() sorts them by first element, which is id (we could pass additional key argument to keep order same). Finally we split sorted results back to two arrays (applying zip again restores initial configuration), assign them to variables and create required dictionary.
CodePudding user response:
Python can do this in one line:
>>> d = {'points' : [[2,1],[3,4], [5,6],[7,8]], 'ids':[[2], [1], [3], [0]]}
>>> d['ids'], d['points'] = zip(*sorted(zip(d['ids'], d['points'])))
>>> d
{'points': ([7, 8], [3, 4], [2, 1], [5, 6]), 'ids': ([0], [1], [2], [3])}
The zip steps brings the ids and points together pairwise. The sorted step orders by the id which is the first element of each pair. The zip(*s) step splits the ids and points and points back into separate sequences.
Note the internal data types have been converted from lists to tuples. If this isn't desired, you can call list to convert them back.
