Jon
Jon

Reputation: 40032

Python ordering a dictionary value

I have this response from a web request:

{'Changes': [{'StartColumn': 34, 'StartLine': 8, 'EndLine': 8, 'NewText': '\n        ', 'EndColumn': 34}, {'StartColumn': 13, 'StartLine': 9, 'EndLine': 9, 'NewText': '', 'EndColumn': 17}, {'StartColumn': 13, 'StartLine': 10, 'EndLine': 10, 'NewText': '', 'EndColumn': 17}]}

In my Python dictionary I get access to the value by data['Changes'] and can loop over each item.

What I would like to do is order the value of Changes to be be ordered by EndLine descending. I looked at Sorted with Reverse=True but I couldn't get it to work.

Any pointers?

Upvotes: 1

Views: 72

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 76887

You could use sorted over the value (the list) for key "Changes".

My guess is that you call sorted over the complete dict currently, which is why it doesn't work.

In [1]: d = {'Changes': [{'StartColumn': 34, 'StartLine': 8, 'EndLine': 8, 'NewText': '\n        ', 'EndColumn': 34}, {'StartColumn': 13, 'StartLine': 9, 'EndLine': 9, 'NewText': '', 'EndColumn': 17}, {'StartColumn': 13, 'StartLine': 10, 'EndLine': 10, 'NewText': '', 'EndColumn': 17}]}

In [2]: d["Changes"] = sorted(d["Changes"], key= lambda x: x["EndLine"], reverse=True)

In [3]: d["Changes"]
Out[3]: 
[{'EndColumn': 17,
  'EndLine': 10,
  'NewText': '',
  'StartColumn': 13,
  'StartLine': 10},
 {'EndColumn': 17,
  'EndLine': 9,
  'NewText': '',
  'StartColumn': 13,
  'StartLine': 9},
 {'EndColumn': 34,
  'EndLine': 8,
  'NewText': '\n        ',
  'StartColumn': 34,
  'StartLine': 8}]

As @Andrea points out, in this situation we could use .sort() to do this in place, and do away with the overhead of creating a new list

In [4]: d = {'Changes': [{'StartColumn': 34, 'StartLine': 8, 'EndLine': 8, 'NewText': '\n        ', 'EndColumn': 34}, {'StartColumn': 13, 'StartLine': 9, 'EndLine': 9, 'NewText': '', 'EndColumn': 17}, {'StartColumn': 13, 'StartLine': 10, 'EndLine': 10, 'NewText': '', 'EndColumn': 17}]}

In [5]: d["Changes"].sort(key=lambda x: x["EndLine"], reverse=True)

In [6]: d["Changes"]
Out[6]: 
[{'EndColumn': 17,
  'EndLine': 10,
  'NewText': '',
  'StartColumn': 13,
  'StartLine': 10},
 {'EndColumn': 17,
  'EndLine': 9,
  'NewText': '',
  'StartColumn': 13,
  'StartLine': 9},
 {'EndColumn': 34,
  'EndLine': 8,
  'NewText': '\n        ',
  'StartColumn': 34,
  'StartLine': 8}]

Upvotes: 3

Related Questions