0

我希望基本上有一个排序的字典列表,如下所示:

similarity = [{'Ben': 49}, {'Moose': 18}, {'Reuven': 39}, {'Cust1': 58}, {'Cust2': 10}, {'Francois': 58}, {'Jim C': 39}, {'Iren': 13}, {'Cust3': 13}]

任何帮助表示赞赏,并提前感谢。

4

3 回答 3

4

您应该在这里使用元组列表:

>>> lst = [d.items()[0] for d in similarity]
>>> lst
[('Ben', 49), ('Moose', 18), ('Reuven', 39), ('Cust1', 58), ('Cust2', 10), ('Francois', 58), ('Jim C', 39), ('Iren', 13), ('Cust3', 13)]

然后你可以像往常一样对它们进行排序。

>>> from operator import itemgetter
>>> sorted(lst, key=itemgetter(1))
[('Cust2', 10), ('Iren', 13), ('Cust3', 13), ('Moose', 18), ('Reuven', 39), ('Jim C', 39), ('Ben', 49), ('Cust1', 58), ('Francois', 58)]

如果需要,您还可以使用单个有序字典来保存值:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(lst, key=itemgetter(1)))
OrderedDict([('Cust2', 10), ('Iren', 13), ('Cust3', 13), ('Moose', 18), ('Reuven', 39), ('Jim C', 39), ('Ben', 49), ('Cust1', 58), ('Francois', 58)])
于 2012-04-14T22:29:46.597 回答
1

这是一种方法。

>>> sorted(similarity, key=lambda x: x.values()[0])
[{'Cust2': 10}, {'Iren': 13}, {'Cust3': 13}, {'Moose': 18}, {'Reuven': 39}, {'Jim C': 39}, {'Ben': 49}, {'Cust1': 58}, {'Francois': 58}]
于 2012-04-14T22:13:47.503 回答
0

我在这方面面临困难。
所以我建议你用这种方法

a = {'Ben': 49}
b =  {'Moose': 18}
ab = {**a, **b}
print(ab)
{'Ben': 49, 'Moose': 18}

1: sorted(ab.values())
[('Ben', 49), ('Moose', 18)]

2: sorted(ab.items())
[18, 49]

于 2020-06-25T09:13:32.873 回答