def handle_order(s): arr = s.split(" ") dict = {} for i in arr: temp = i.split(":") if temp[1] == "0": dict["0"] = temp[0] elif temp[1] == "1": dict["1"] = temp[0] elif temp[1] == "2": dict["2"] = temp[0] a = sorted(dict.items(),key= lambda d :d[0]) return a s= "SQS:1 HTTPS:0 LAMBDA:2" print(handle_order(s))