sort a Python dictionary by value

首先要明确一点,Python的dict本身是不能被sort的,更明确地表达应该是“将一个dict通过操作转化为value有序的列表”

有以下几种方法:

1.

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
#sorted by value

sorted_x = sorted(x.items(), key=operator.itemgetter(0))
#sorted by key

2.

sorted(dict1, key=dict1.get)

3.

sorted(d.items(), key=lambda x: x[1])

4.

sorted([(value,key) for (key,value) in mydict.items()])

5. Use OrderedDict

>>> # regular unsorted dictionary
>>> d = {‘banana‘: 3, ‘apple‘: 4, ‘pear‘: 1, ‘orange‘: 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([(‘apple‘, 4), (‘banana‘, 3), (‘orange‘, 2), (‘pear‘, 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([(‘pear‘, 1), (‘orange‘, 2), (‘banana‘, 3), (‘apple‘, 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([(‘pear‘, 1), (‘apple‘, 4), (‘orange‘, 2), (‘banana‘, 3)])
时间: 2024-12-29 05:53:38

sort a Python dictionary by value的相关文章

Python dictionary implementation

Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/ August 29, 2011 This post describes how dictionaries are implemented in the Python language. Dictionaries are indexed by keys and they can be seen as

[leetcode]Sort List @ Python

原题地址:http://oj.leetcode.com/problems/sort-list/ 题意:链表的排序.要求:时间复杂度O(nlogn),空间复杂度O(1). 解题思路:由于题目对时间复杂度和空间复杂度要求比较高,所以查看了各种解法,最好的解法就是归并排序,由于链表在归并操作时并不需要像数组的归并操作那样分配一个临时数组空间,所以这样就是常数空间复杂度了,当然这里不考虑递归所产生的系统调用的栈.   这里涉及到一个链表常用的操作,即快慢指针的技巧.设置slow和fast指针,开始它们都

[leetcode]Insertion Sort List @ Python

原题地址:http://oj.leetcode.com/problems/insertion-sort-list/ 题意:对链表进行插入排序. 解题思路:首先来对插入排序有一个直观的认识,来自维基百科. 代码循环部分图示: 代码: class Solution: # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if not head: return head dummy = Lis

[leetcode]Sort Colors @ Python

原题地址:https://oj.leetcode.com/problems/sort-colors/ 题意: Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integer

[Python] Heap Sort in Python

代码: #! /usr/bin/env python #coding=utf-8 import random,copy def heap_sort_helper(lst,left,right): # max heapify current_value = lst[left] child = 2 * left + 1 while (child <= right): if (child < right and lst[child] < lst[child+1]): child = child

python --dictionary

我们要介绍一个新的类,词典 (dictionary).与列表相似,词典也可以储存多个元素.这种储存多个元素的对象称为容器(container). 基本概念 常见的创建词典的方法: >>>dic = {'tom':11, 'sam':57,'lily':100} >>>print type(dic) 词典和表类似的地方,是包含有多个元素,每个元素以逗号分隔.但词典的元素包含有两部分,键和值,常见的是以字符串来表示键,也可以使用数字或者真值来表示键(不可变的对象可以作为键)

Simple Python Dictionary :)

摘自 http://github.com/panweizeng/home/blob/master/code/python/dict/dict.py 支持简单的Ch to En 和En to Ch我把它放在 /usr/bin/dict 1234567891011 $ dict 白痴 单词:白痴 音标: bái chī 释义:idiot idiocy 例句:他很聪明,但有时举止像是白痴. 翻译:He is intelligent, but sometimes he behaves like an i

Hash table and Python dictionary

One of the most useful Python collections is the dictionary, which is an associative data type where you can store key-data pairs. It is implemented using hash tables. Hash table is a collection of items which are stored in such a way as to make it e

SAE 本地环境报错[python][dictionary update sequence element #0 has length 1; 2 is required]

本地搭建SAE的python环境时,总是报如下错误: 1 F:\workspace\dev\python\frikyskice\1>dev_server.py 2 Traceback (most recent call last): 3 File "C:\Python27\Scripts\dev_server.py", line 205, in <module> 4 main(options) 5 File "C:\Python27\Scripts\dev_