[英]bubble sorting in dictionary in python
I am trying to do bubble sort in descending order 我正在尝试按降序排列气泡
input={"m":1,"i":4,"s":4,"P":2}
output={"i":4,"s":4,"p":2,"m":1}
but a type error occurs. 但是发生类型错误。 How can I do this? 我怎样才能做到这一点?
Below is the code: 下面是代码:
dict={"m":1,"i":4,"s":4,"P":2}
for key,value in dict.items():
if(dict[key]<dict[key+1]):
temp=dict[key]
dict[key]=dict[key+1]
dict[key+1]=temp
print(dict)
A dictionary has no order : if you add/remove/update elements in a dictionary, the order in which the keys are iterated can change. 字典没有顺序 :如果您在字典中添加/删除/更新元素,则键的迭代顺序可以更改。
So you can not "sort" a dictionary. 因此,您不能对字典进行“排序”。 What you can do however, is for example sort a list of 2-tuples , like: 但是,您可以做的是例如对2元组的列表进行排序,例如:
my_list = list(my_dict.items())
We then retrieve: 然后,我们检索:
>>> my_list
[('m', 1), ('i', 4), ('s', 4), ('P', 2)]
and thnen we can sort the list (for example with bubblesort) like: 然后我们可以像这样对列表进行排序(例如,用bubbleort排序):
for mx in range(len(my_list)-1, -1, -1):
swapped = False
for i in range(mx):
if my_list[i][1] < my_list[i+1][1]:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
swapped = True
if not swapped:
break
Then afterwards, we have: 然后,我们有:
>>> my_list
[('i', 4), ('s', 4), ('P', 2), ('m', 1)]
do you mean something like this? 你的意思是这样吗?
dict={"m":1,"i":4,"s":4,"P":2}
sorted_values = sorted(dict.values(),reverse = True)
print sorted_values
But this isn't "manual" bubble sort. 但这不是“手动”冒泡排序。 So if you have to to bubble sort this by your own just use the list of values via 因此,如果您必须自行冒泡排序,只需使用通过
values = dict.values()
And then sort them ;) 然后对它们进行排序;)
As timgeb already mentioned in a comment, I'm sorry didnt see the comment before I wrote this post. 正如timgeb在评论中已经提到的那样,很抱歉,在我写这篇文章之前没有看到评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.