#字典value值排序,key值排序 from random import * dict1 = {x:randint(5,12) for x in "aijwt"} dict2 = {randint(5,12):y for y in "aibjwte"} print (‘dict1:‘,dict1) print (‘dict2:‘,dict2) print ("将字典按value倒序显示,办法(collections的Counter):") from collections import Counter dict11 = Counter(dict1).most_common() #转为列表 dict22 = Counter(dict2).most_common() #转为列表 print(‘dict1按value倒序显示:‘,dict(dict11)) #转为字典显示 print(‘dict2按value倒序显示:‘,dict(dict22)) #转为字典显示 print ("将字典按key正序显示") dict12 = list(dict1.items()) dict12.sort(key=lambda x:x[0]) #按照列表中元组元素的的第一个元素排序 print(‘dict1按key正序显示:‘,dict12) print ("将字典按value正序显示") dict13 = list(dict1.items()) dict13.sort(key=lambda x:x[1]) #按照列表中元组元素的的第二个元素排序 print(‘dict1按value正序显示:‘,dict13) print(‘\n==========================分割一下=================================\n‘) a1= list(dict1) #字典key转为列表 a2= list(dict1.items()) #字典元素转为列表 a3= [i for i in dict1.items()] #字典元素转为列表 print(‘dict1:‘,dict1) print(‘list(dict1) :‘,a1) print(‘list(dict1.items()) :‘,a2) print(‘[i for i in dict1.items()]:‘,a3) #列表转为字典 print(dict(a3))
结果:
dict1: {‘a‘: 7, ‘i‘: 7, ‘j‘: 7, ‘w‘: 11, ‘t‘: 11} dict2: {12: ‘j‘, 5: ‘i‘, 8: ‘b‘, 9: ‘w‘, 7: ‘t‘, 11: ‘e‘} 将字典按value倒序显示,办法(collections的Counter): dict1按value倒序显示: {‘w‘: 11, ‘t‘: 11, ‘a‘: 7, ‘i‘: 7, ‘j‘: 7} dict2按value倒序显示: {9: ‘w‘, 7: ‘t‘, 12: ‘j‘, 5: ‘i‘, 11: ‘e‘, 8: ‘b‘} 将字典按key正序显示 dict1按key正序显示: [(‘a‘, 7), (‘i‘, 7), (‘j‘, 7), (‘t‘, 11), (‘w‘, 11)] 将字典按value正序显示 dict1按value正序显示: [(‘a‘, 7), (‘i‘, 7), (‘j‘, 7), (‘w‘, 11), (‘t‘, 11)] ==========================分割一下================================= dict1: {‘a‘: 7, ‘i‘: 7, ‘j‘: 7, ‘w‘: 11, ‘t‘: 11} list(dict1) : [‘a‘, ‘i‘, ‘j‘, ‘w‘, ‘t‘] list(dict1.items()) : [(‘a‘, 7), (‘i‘, 7), (‘j‘, 7), (‘w‘, 11), (‘t‘, 11)] [i for i in dict1.items()]: [(‘a‘, 7), (‘i‘, 7), (‘j‘, 7), (‘w‘, 11), (‘t‘, 11)] {‘a‘: 7, ‘i‘: 7, ‘j‘: 7, ‘w‘: 11, ‘t‘: 11} Process finished with exit code 0
原文地址:https://www.cnblogs.com/jxba/p/11840798.html
时间: 2024-10-11 03:35:44