0

I need to sort a list of dictionaries by x and y co-ordinates.

My list is:

xy_list = [{'x':40,'y':50},{'x':40,'y':10},{'x':40,'y':50},{'x':20,'y':10},{'x':20,'y':30},{'x':10,'y':10}]

The desired output is:

xy_list = [{'x':10,'y':10},{'x':20,'y':10},{'x':20,'y':30},{'x':40,'y':10},{'x':40,'y':30},{'x':40,'y':50}]

How do I get this sorted?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alan_blk
  • 163
  • 1
  • 6

2 Answers2

0

You will want to sort your data like this:

xy_list = [{'x':40,'y':50},{'x':40,'y':10},{'x':40,'y':50},{'x':20,'y':10},{'x':20,'y':30},{'x':10,'y':10}]
xy_list.sort(key=lambda item:item['x'])

the key defines a way to get the item to compare, in your case you need to get an item from a dict so here item['x'] you can write what ever your key is,x or y in your case

Nullman
  • 4,179
  • 2
  • 14
  • 30
0

You can convert it to dataframe and use sort_values and then convert to dict by records.

In [13]: xy_list = [{'x':40,'y':50},{'x':40,'y':10},{'x':40,'y':50},{'x':20,'y':10},{'x':20,'y':30},{'x':10,'y':10}]

In [14]: import pandas as pd

In [15]: df = pd.DataFrame(xy_list)

In [16]: new_df = df.sort_values(['x','y'])

In [17]: new_df.to_dict('records')
Out[17]:
[{'x': 10, 'y': 10},
 {'x': 20, 'y': 10},
 {'x': 20, 'y': 30},
 {'x': 40, 'y': 10},
 {'x': 40, 'y': 50},
 {'x': 40, 'y': 50}]
everfight
  • 420
  • 3
  • 10