Mots clés : pythonsortingdictionarypython
92
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} >>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
>>> dict(sorted(x.items(), key=lambda item: item[1])) {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0))
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=lambda kv: kv[1])
import collections sorted_dict = collections.OrderedDict(sorted_x)
86
from collections import defaultdict d = defaultdict(int) for w in text.split(): d[w] += 1
for w in sorted(d, key=d.get, reverse=True): print(w, d[w])
70
sorted(d.items(), key=lambda x: x[1])
sorted(d.items(), key=lambda x: x[1], reverse=True)
d = {'one':1,'three':3,'five':5,'two':2,'four':4} a = sorted(d.items(), key=lambda x: x[1]) print(a)
[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
61
sorted(d.values())
from operator import itemgetter sorted(d.items(), key=itemgetter(1))
51
>>> d = {"third": 3, "first": 1, "fourth": 4, "second": 2} >>> for k, v in d.items(): ... print "%s: %s" % (k, v) ... second: 2 fourth: 4 third: 3 first: 1 >>> d {'second': 2, 'fourth': 4, 'third': 3, 'first': 1}
>>> from collections import OrderedDict >>> d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
>>> for k, v in d_sorted_by_value.items(): ... print "%s: %s" % (k, v) ... first: 1 second: 2 third: 3 fourth: 4 >>> d_sorted_by_value OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])