4
[ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ]

How can I sort according to Price..?

Rakesh
  • 78,594
  • 17
  • 67
  • 103
Ajay Shewale
  • 149
  • 2
  • 13

2 Answers2

2
data = [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { "Price": 227243.14, "Agents": [ 4056270],} } ]
newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"])
print(newlist)

Output:

[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]

or in descending order

newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"], reverse=True)
print(newlist)
#[{'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}]
Rakesh
  • 78,594
  • 17
  • 67
  • 103
  • My list is not in the same format, some of PricingOptions have more than one entries of [Price, Agent]. So the solution you have provided it will show the key error for such cases. for example, data = [ { "PricingOptions": { "Price": 51540.72, "Agents": [ 4056270 ] } }, { "PricingOptions": { ["Price": 227243.14, "Agents": [ 4056270], ["Price":454545 "Agents": [ 4056454]} } ] – Ajay Shewale May 11 '18 at 06:55
2

You can use sorted method by applying a lambda expression.

sort_list = sorted(data, key=lambda elem: elem['PricingOptions']["Price"])

Output

[{'PricingOptions': {'Price': 51540.72, 'Agents': [4056270]}}, {'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}}]

If you want to sort the list descending you just need to assign True to reverse property.

Mihai Alexandru-Ionut
  • 44,345
  • 11
  • 88
  • 115