[英]Sorting a dictionary of lists
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:我想找到一种基于timeOfArrival
键对其进行排序的方法,如下例所示:
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 (ie "timeOfArrival": [4, 4, 3, 1]}
) I get a dictionary bigger than the one I gave it in the beginning.我尝试的是对timeOfArrival
进行排序,然后我尝试在my_dict
中循环,这样我就可以将值重新排列到它们的“正确”位置,这是可行的,但是如果我有重复的值(即"timeOfArrival": [4, 4, 3, 1]}
) 我得到了一本比我一开始给它的字典更大的字典。
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
I think this is what you're looking for.我想这就是你要找的。 It determines the sort order by getting the indices of the sorted arrival times.它通过获取已排序到达时间的索引来确定排序顺序。 I then uses the index order to sort all of the lists in the dict.然后我使用索引顺序对字典中的所有列表进行排序。
order = [i for i, _ in sorted(enumerate(my_dict['timeOfArrival']), key=lambda x: x[1])]
for key, value in my_dict.items():
if key != 'timeOfArrival': # Expected output shows timeOfArrival should not be sorted
my_dict[key] = [value[i] for i in order]
You need to zip then sort:您需要 zip 然后排序:
# your unsorted dictionary
my_dict = {"user": [1, 2, 3, 4], "sex": ['M', 'F', 'O', 'F'],"timeOfArrival": [4, 1, 3, 8]}
# your sorted dictionary
sorted_dict = {}
# zip lists, sort by timeOfArrival and unpack into the new dictionary
sorted_dict["user"], sorted_dict["sex"], sorted_dict["timeOfArrival"] = zip(*sorted(zip(my_dict["timeOfArrival"], my_dict["user"], my_dict["sex"])))
# convert the tuples in the new dictionary into a list
sorted_dict["user"] = list(sorted_dict["user"])
sorted_dict["sex"] = list(sorted_dict["sex"])
sorted_dict["timeOfArrival"] = list(sorted_dict["timeOfArrival"])
# you're done ;-)
print(sorted_dict)
# {'user': [1, 3, 4, 8], 'sex': [2, 3, 1, 4], 'timeOfArrival': ['F', 'O', 'M', 'F']}
Then just reconstruct your dictionary with these newly sorted lists.然后用这些新排序的列表重建你的字典。
The data can be merged with zip
.数据可以与zip
合并。
my_dict = {
"user": [1, 2, 3, 4],
"sex": ['M', 'F', 'O', 'F'],
"timeOfArrival": [4, 1, 3, 8]}
print(list(zip(my_dict['timeOfArrival'], my_dict['user'], my_dict['sex'])))
This will give you这会给你
[(4, 1, 'M'), (1, 2, 'F'), (3, 3, 'O'), (8, 4, 'F')]
This can be sorted.这可以排序。
data = list(sorted(zip(my_dict['timeOfArrival'], my_dict['user'], my_dict['sex'])))
print(data)
Result:结果:
[(1, 2, 'F'), (3, 3, 'O'), (4, 1, 'M'), (8, 4, 'F')]
Unpack the sorted data:解包排序后的数据:
data = list(zip(*data))
Now data
looks like this:现在data
看起来像这样:
[(1, 3, 4, 8), (2, 3, 1, 4), ('F', 'O', 'M', 'F')]
Finally the sorted data must be put back to the matching dictionary entry最后必须将排序后的数据放回匹配的字典条目
my_dict['user'] = list(data[1])
my_dict['sex'] = list(data[2])
Now my_dict
contains {'user': [2, 3, 1, 4], 'sex': ['F', 'O', 'M', 'F'], 'timeOfArrival': [4, 1, 3, 8]}
.现在my_dict
包含{'user': [2, 3, 1, 4], 'sex': ['F', 'O', 'M', 'F'], 'timeOfArrival': [4, 1, 3, 8]}
.
Compressed version压缩版
my_dict = {
"user": [1, 2, 3, 4],
"sex": ['M', 'F', 'O', 'F'],
"timeOfArrival": [4, 1, 3, 8]}
data = list(zip(*sorted(zip(my_dict['timeOfArrival'], my_dict['user'], my_dict['sex']))))
my_dict['user'] = list(data[1])
my_dict['sex'] = list(data[2])
I suggest you to use " Insertion Sort " algorithm.我建议你使用“插入排序”算法。
I modified it to fit into your example, it seeems to perform as you wish:我对其进行了修改以适合您的示例,它似乎可以按照您的意愿执行:
my_dict = {"user": [2,3,1,4 ], "sex": ['F', 'O', 'M', 'F' ],"timeOfArrival": [4, 1, 3, 8]}
def insertion_sort(my_dict):
for k in range(1, len(my_dict['timeOfArrival'])):
cur_timeOfArrival = my_dict['timeOfArrival'][k]
cur_sex = my_dict['sex'][k]
cur_user = my_dict['user'][k]
j=k
while j > 0 and my_dict['timeOfArrival'][j-1] > cur_timeOfArrival:
my_dict['timeOfArrival'][j] = my_dict['timeOfArrival'][j-1]
my_dict['sex'][j] = my_dict['sex'][j-1]
my_dict['user'][j] = my_dict['user'][j-1]
j -= 1
my_dict['timeOfArrival'][j] = cur_timeOfArrival
my_dict['sex'][j] = cur_sex
my_dict['user'][j] = cur_user
return my_dict
print(insertion_sort(my_dict))
#{'user': [3, 1, 2, 4], 'sex': ['O', 'M', 'F', 'F'], 'timeOfArrival': [1, 3, 4, 8]}
Regards.问候。
Thing is that I just needed to sort my dictionary and to keep my lists separate from one another, so combining the lists like so:事情是我只需要对我的字典进行排序并将我的列表彼此分开,所以像这样组合列表:
[(4, 1, 'M'), (1, 2, 'F'), (3, 3, 'O'), (8, 4, 'F')]
was out of the question.是不可能的。
Thank you all for your time and more importantly, thanks to @MauriceMeyer I got it working.谢谢大家的时间,更重要的是,感谢@MauriceMeyer,我让它工作了。
def sortDict(dictionary={},name="test"):
sortedList=sorted(my_dict[name])
dictKeys=list(dictionary.keys())
testDict={}
for key in dictKeys:
testDict[key]=[x for _,x in sorted(zip(my_dict[name],my_dict[key]))]
return testDict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.