0

I have the following code (Python 2.7):

response2 = requests.get(...)
sample_object = pd.DataFrame(response2.json())['results'].to_dict()

This creates a dict from my DataFrame and I'm creating a Json from it However it is not sorted:

enter image description here

How can I sort it by key? meaning isGift before ShippingAddress_city etc...

I saw privious answers like this but I can't manage to do it in my code... tried also to_dict(into=ordered) but nothing happens.

Is there an easy way to sort it from the start? Or must I sort it only after creation and if so how do I do that?

jpp
  • 159,742
  • 34
  • 281
  • 339
jack
  • 821
  • 5
  • 16
  • 28

1 Answers1

1

You can use sorted with a custom key and feed into collections.OrderedDict:

from collections import OrderedDict

sample_object = pd.DataFrame(response2.json())['results'].to_dict()
sorted_object = OrderedDict(sorted(sample_object.iteritems(), key=lambda x: x[0]))

Note that dictionaries before Python 3.7 are considered unordered. Since OrderedDict is a subclass of dict, the above method should not cause issues with downstream operations.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • I'm using Python 2.7 – jack Jul 03 '18 at 14:29
  • @jack, Then this answer will help, see [OrderedDict docs in 2.7](https://docs.python.org/2/library/collections.html#ordereddict-objects) :). Since you are using 2.7, you can use `dict.iteritems` as per update. – jpp Jul 03 '18 at 14:30