1

I have the following piece of code in Python 3.4

message = {'function':'TIME_SERIES_INTRADAY',
'symbol':'MSFT',
'interval':'15min',
'apikey':'demo'}

for key1 in message:
    print(key1)

The above code is always printing the keys in different order every time I run it. Is there a way to make it in order as it is assigned?

naseefo
  • 720
  • 1
  • 9
  • 30

2 Answers2

2

Python dictionary keys are not ordered by default. Use an ordered dict if you need them to be consistent and in the order with which you populate the dict.

Edit: OrderedDict has been introduced since Python 3.1 and is still valid even at Python 3.6

You can learn more about it here.

Imma
  • 122
  • 1
  • 9
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42
  • 2
    Your belief is true, the dicts in 3.6 maintain the order. Beware though, if you start poping/inserting elements eventually you may trigger a dict re-packing that will scramble the order. If you REALLY want to be sure, use OrderedDict. If your dictionary is constant, you may use normal dict in 3.6 – agomcas Mar 27 '18 at 05:59
  • Basically what I am trying to do is to receive a JSON formatted data from an stock market API. The content in the JSON format is ordered with each key representing a 1 minute time increment. I need to get that in order in Python. What I thought was to convert this into a dictionary. – naseefo Mar 27 '18 at 06:30
  • An ordereddict would keep the keys in the order that you add them. If you want to do something else (such as deserialize json into an ordered format), you should add that onto the question :) – Paul Becotte Mar 27 '18 at 06:34
  • I was able to get this in order with this code: data = json.loads(r.text, object_pairs_hook=OrderedDict) where r.text is the json i got from the web service API – naseefo Mar 27 '18 at 07:07
1

To expand on my comment, in 3.6 this dictionary:

a = {r: r for r in range(100)}

prints as 0-99

However if we do:

for r in range(50):
    a.pop(r)

for r in range(10):
    a[r] = r

for r in range(10):
    a[r + 100] = r + 100

We find the surprising situation that it prints 0-9, 50-99, 100-109 so the original 50-99 are kept in the insertion order, but somehow the additions afterwards where put at the beginning (0-9) and then at the end (100-109).

agomcas
  • 695
  • 5
  • 12