0

I have a code in python, that creates a dictionary with some keys and values. But, I need to have the values ordered in same order as they was added. So code

def getdataready():
    data = {}
    data["cputemp"] = str(getcputemp())
    data["cas"] = str(datetime.datetime.now()).replace(" ", "%20")
    data["fan"] = str(fanstate())
    data["pstemp"] = str(getPStemp())
    #there are some more keys added
    return data

declares the dictionary and returns it. But when I run the code, the returned dictionary is ordered without any rules (pstemp, cas, cputemp, venkovniteplota, fan, pokojovatelota) How can I order they in the order of declaration(cputemp, cas, fan, pstemp,...)? I need it, because in this order, the dictionary is sended to webserver ( http://parman.moxo.cz/index.php?page=info using wget and dictionary is converted into url and given to PHP as values in $GET) and there is displayed in the same order as it was received and I'd like to have it in this order Thanks.

parman
  • 127
  • 1
  • 3
  • 11
  • Also, use snake case for the method name `def get_data_ready()` – Gustavo Barbosa Jan 18 '15 at 20:20
  • @Kasra i get 404, maybe wrong link? – parman Jan 18 '15 at 20:21
  • To control the order of items in a dictionary, you can use an `OrderedDict` from the `collections` module. It exactly preserves the original insertion order of data when iterating. : `from collections import OrderedDict data= OrderedDict()` read more https://docs.python.org/3.4/library/collections.html#collections.OrderedDict – Mazdak Jan 18 '15 at 20:28

1 Answers1

1

Use collections.OrderedDict. It provides the functionality you asked for and keeps the keys in the order they were added.

TidB
  • 1,749
  • 1
  • 12
  • 14
  • Thanks you all, only needed to import collections. (for some reason, I can't accept answer right now, so wait) – parman Jan 18 '15 at 20:27