Python的字典排序和有序字典
输入:
a = {3:6, 1:4, 5:5}
输入a,
输出:
{1: 4, 3: 6, 5: 5}
字典排序:
- 输入:
sorted(a, cmp,reverse = True)
输出:[5, 3, 1],为元组;a为{1: 4, 3: 6, 5: 5};一般用法:for i in sorted(a,cmp): print i, a[i];
- 输入:
sorted(a.items(), key = lambda t:t[0],reverse = True)输出:[(5, 5), (3, 6), (1, 4)],为元组;a为{1: 4, 3: 6, 5: 5};
- 输入:
sorted(a.items(), key = lambda t:t[1])输出:[(3, 6), (5, 5), (1, 4)],为元组;a为{1: 4, 3: 6, 5: 5};
- 输入:
b = a.items(), b.sort(reverse = True)
输入b,输出:[(5, 5), (3, 6), (1, 4)],为元组;a为{1: 4, 3: 6, 5: 5};
有序字典:
from collections import OrderedDict b = OrderedDict(sorted(a.items(), key = lambda t:t[1]))
输入b,输出:
OrderedDict([(1, 4), (5, 5), (3, 6)])
b为字典;a为{1: 4, 3: 6, 5: 5}
浙公网安备 33010602011771号