现在的位置: 首页 > 综合 > 正文

005_001 Python 对字典排序

2017年12月10日 ⁄ 综合 ⁄ 共 291字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

#对字典排序
#排序尽量使用list的sort
#搜索尽量使用dict
print cmp((1,2,3),(1,2,5))
print cmp((1,2,3),(1,2,3))


#解决方案 先排序keys再根据keys获取值
def sortedDictValues(adict):
    keys=adict.keys()
    keys.sort()
    return [adict[key] for key in keys]

adict={1:2,7:3,2:4,0:6}

print sortedDictValues(adict)

打印结果如下:

中国
-1
0
[6, 2, 4, 3]

抱歉!评论已关闭.