Home  >  Article  >  Backend Development  >  python对字典进行排序实例

python对字典进行排序实例

WBOY
WBOYOriginal
2016-06-16 08:41:451020browse

本文实例讲述了python对字典进行排序的方法,是非常实用的技巧。分享给大家供大家参考。

具体实现方法如下:

import itertools 
thekeys = ['b','a','c'] 
thevalues = ['bbb','aaa','cccc'] 
 
d = dict(itertools.izip(thekeys,thevalues)) #创建字典 
print d 
 
def sortedDictValue(adict): 
  keys = adict.keys() 
  keys.sort() 
  return map(adict.get,keys) 
 
print sortedDictValue(d)
import itertools
thekeys = ['b','a','c']
thevalues = ['bbb','aaa','cccc']
def sortedDictValue(adict): #自定义的排序函数,先取得字典的keys(),然后对keys进行排序,最后根据排序好的keys取字典的值 
  keys = adict.keys() 
  keys.sort() 
  return map(adict.get,keys)#只有这里不同,这里调用内置的map函数,对每个keys中的项目,调用adict.get函数,返回一个列表  
 
print sortedDictValue(d) 
#打印出相同的结果 

程序运行结果为:

{'a': 'aaa', 'c': 'cccc', 'b': 'bbb'}
['aaa', 'bbb', 'cccc']
['aaa', 'bbb', 'cccc']

希望本文所述对大家Python程序设计的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn