美文网首页
How to sort a Python dict by val

How to sort a Python dict by val

作者: import_hello | 来源:发表于2018-10-10 22:12 被阅读0次
# How to sort a Python dict by value
# (== get a representation sorted by value)

>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

相关文章

网友评论

      本文标题:How to sort a Python dict by val

      本文链接:https://www.haomeiwen.com/subject/rwkboftx.html