-2

I made a list

data = [{"type":"house", "cost":500, "extra":False, "order":1}, 
{"type":"condo", "cost":40, "extra":False, "order":4}, 
{"type":"house", "cost":120, "extra":True, "order":2}, 
{"type":"house", "cost":800, "extra":True, "order":3}]

and want to sort the data by order key

how would you sort it out?

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
mmm
  • 11
  • 2

2 Answers2

0

You're not sorting a dictionary, you are sorting a list of dictionaries.

Try this:

data = [{"type":"house", "cost":500, "extra":False, "order":1}, 
{"type":"condo", "cost":40, "extra":False, "order":4}, 
{"type":"house", "cost":120, "extra":True, "order":2}, 
{"type":"house", "cost":800, "extra":True, "order":3}]

length = len (data)
for index1 in range (length) :
    for index2 in range (length) :
        if data [index2]['order'] > data [index1]['order'] :
            data [index2], data [index1] = data [index1], data [index2]
print (data)
bashBedlam
  • 1,402
  • 1
  • 7
  • 11
0

If you are trying to sort a list of dictionaries, try the following:

data = [
    {"type": "house", "cost": 500, "extra": False, "order": 1}, 
    {"type": "condo", "cost": 40, "extra": False, "order": 4}, 
    {"type": "house", "cost": 120, "extra": True, "order": 2}, 
    {"type": "house", "cost": 800, "extra": True, "order": 3},
]

data.sort(key=lambda x: x["order"])  # sort by the value of order

If you want the keys in each dictionary in the list to be sorted, you'll have to use OrderedDict.

fractals
  • 816
  • 8
  • 23