擅长:python、mysql、java
<p>下面是一个按值的长度然后按值排序字典的示例</p>
<p>例1:</p>
<pre><code>d = {'ATCG':[1,2,3], 'ATTT':[1,3,5], 'TCC':[4,5,6], 'GCT':[2,4,8], 'AC':[7,8,9]}
# Use tuple to specify multiple criteria to sort upon
# i.e. first by length, then by key length,
# then value (i.e. t[0] is key, t[1] is value)
value_sort = sorted(d.items(), key=lambda t: (len(t[0]), t[1]))
for k, v in value_sort:
print(k, v)
</code></pre>
<p>输出</p>
<pre><code>AC [7, 8, 9]
GCT [2, 4, 8]
TCC [4, 5, 6]
ATCG [1, 2, 3]
ATTT [1, 3, 5]
</code></pre>
<p>例2:</p>
<pre><code>d = {"one": [(1,3),(1,4)],
"two": [(1,2),(1,2),(1,3)],
"three": [(1,1)]}
# Use tuple to specify multiple criteria to sort upon
# i.e. first by length, then by value
# t[1] is value of dictionary entry
value_sort = sorted(d.items(), key=lambda t: (len(t[1]), t[1]))
for k, v in value_sort:
print(k, v)
</code></pre>
<p>输出</p>
<pre><code>three [(1, 1)]
one [(1, 3), (1, 4)]
two [(1, 2), (1, 2), (1, 3)]
</code></pre>