I have the following dictionary:
my_dict = {"user": [1, 2, 3, 4], "sex": ['M', 'F', 'O', 'F'],"timeOfArrival": [4, 1, 3, 8]}
and I want to find a way to sort it based on the timeOfArrival
key, like the following example:
my_dict = {"user": [2,3,1,4 ], "sex": ['F', 'O', 'M', 'F' ],"timeOfArrival": [4, 1, 3, 8]}
Right now I'm having trouble of thinking a straight-forward solution.
What I've tried is sorting the timeOfArrival
and after that I tried looping inside my_dict
so I can rearrange the values to their 'correct' positions, which works, but if I have duplicated values (i.e "timeOfArrival": [4, 4, 3, 1]}
) I get a dictionary bigger than the one I gave it in the beginning.
Is there a better way to sort my dictionary?
def sortDict(dictionary={},name="test"):
sortedList=sorted(my_dict[name])
dictKeys=list(dictionary.keys())
testDict={}
for i in dictKeys:
testDict[i]=[]
for key in dictKeys:
for item in sortedList:
for pos in range(0,len(dictionary[name])):
if(item==dictionary[name][pos]):
testDict[key].append(dictionary[key][pos])
return testDict