Use OrderedDict() as suggested in comments, but correctly:
from collections import OrderedDict
d = OrderedDict([('name', 'satendra'), ('occupation', 'engineer'), ('age', 27)])
You define it as you would like your output to be. Then you use it as you would normal dictionary.
And when you want your list of tuples back, you do:
t = d.items()
You can use this solution when you know what keys to expect and you cannot use OrderedDict():
def sortdict (d, keys=["name", "occupation"]):
mx = len(keys)
def customsortkey (key):
try: return keys.index(key)
except: return mx
kys = sorted(d, key=customsortkey)
return [(key, d[key]) for key in kys]
This function will sort everything in the input dictionary "d" according to the order set by "keys" list. Any item in the dictionary, without its key present in list "keys" will be put to the end of the output in arbitrary order. You can indicate keys that aren't present in the dictionary,
The output will be a list of tuples (key, value) as you require.
This is one of possible solutions and it is far from ideal. I.e. we can start a discussion about its efficiency and overhead. But really, in practice it will work just fine, and will handle any unexpected keys nicely.
More efficient version of this function would be to use a dictionary to denote the order of keys instead of the list. A dictionary having the key in question for a key and an sorting index for its value.
Like this:
def sortdict (d, keys={"name": 0, "occupation": 1}):
mx = len(keys)
kys = sorted(d, key=lambda k: keys.get(k, mx))
return [(key, d[key]) for key in kys]