import heapq
#对字典排序
def sort_dict(dict1): <pre name="code" class="python"><strong> <span style="font-family: Arial, Helvetica, sans-serif;">#[1]每个函数体与上面的元素最好保持两行距离 </span></strong>
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="python"><strong> #[2]函数名和参数都要小写,且应该用下划线分割单词</strong>
<pre name="code" class="python"><strong> #[3]运算符号,两边空格以及逗号后空格<span style="font-family: Arial, Helvetica, sans-serif;"> </span></strong>
<pre name="code" class="python"><strong> #[4]缩进应该以4格为单位</strong>
keys = list(dict1.keys()) keys.sort() print(keys) for key in keys: dict1[key] print(dict1.items())#对列表进行排序,并保证每次加入新数据后,列表顺序正确def sort_list_add_data(new_list1, data): new_list2 = [] heapq.heapify(new_list1) heapq.heappush(new_list1, data) #以下pop出元素个数是可定的,可以根据获得元素 while new_list: new_list2.append(heapq.heappop(new_list1)) return new_list2if __name__ == "__main__": #new_dict = {'Python': 3, 'C': 4, 'C++': 3, 'C#': 5,'Perl':1,'Java':2} #sort_dict(new_dict) new_list = [1, 983, 234, 23, 1142, 32, 45, 25, 52] new_list.sort() new_list = sort_list_add_data(new_list, 777) print(new_list)