问题

怎样在数据字典中执行一些计算操作(从而实现求最小值、最大值或排序等等)?

如何能根据某个或某几个字典字段来排序一个字典列表?

如何创建一个字典,并且在迭代或序列化这个字典的时候能够控制元素的顺序?

解决方案

zip( )函数

operator模块的itemgetter函数

OrderedDict 有序字典

zip( )

1. 为了对字典值执行计算操作,通常需要使用zip( )函数先将键和值反转过来

2. 从而我们能将zip和sorted( )、max( )、min( )函数结合使用,来实现排列字典数据

prices = {
'ACME': 37.20,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
} print(min(prices),max(prices)) #直接对字典执行普通的数学运算,其只会对key操作
AAPL IBM print(min(prices.values()),max(prices.values())) #可通过字典的values函数解决,但输出时只能看到values
10.75 612.78 print(min(prices,key=lambda x:prices[x])) #可通过min/max的key属性函数解决,但输出同样不好看
FB print(min(zip(prices.values(),prices.keys()))) #先通过zip()将字典”反转”为(value,key)的元组序列
(10.75, 'FB') print(sorted(zip(prices.values(),prices.keys()))) #若恰巧出现values相同的情况,则根据key的排序结果返回
[(10.75, 'FB'), (37.2, 'ACME'), (37.2, 'HPQ'), (205.55, 'IBM'), (612.78, 'AAPL')]

3. 执行这些计算的时候,需要注意的是zip( )函数创建的是一个只能访问一次的迭代器

prices_and_names=zip(prices.values(),prices.keys())

print(max(prices_and_names))
(612.78, 'AAPL') print(max(prices_and_names)) #第二次再用就报错了
ValueError: max() arg is an empty sequence

operator模块的itemgetter函数

1. sorted(rows,key=itemgetter)

from operator import itemgetter
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
] #根据任意的字典字段key来排序
rows_by_uid=sorted(rows,key=itemgetter('uid'))
print(rows_by_uid)
[{'uid': 1001, 'lname': 'Cleese', 'fname': 'John'}, {'uid': 1002, 'lname': 'Beazley', 'fname': 'David'}, {'uid': 1003, 'lname': 'Jones', 'fname': 'Brian'}, {'uid': 1004, 'lname': 'Jones', 'fname': 'Big'}] #也支持多个 keys
rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
print(rows_by_lfname)
[{'uid': 1002, 'lname': 'Beazley', 'fname': 'David'}, {'uid': 1001, 'lname': 'Cleese', 'fname': 'John'}, {'uid': 1004, 'lname': 'Jones', 'fname': 'Big'}, {'uid': 1003, 'lname': 'Jones', 'fname': 'Brian'}] #应当注意,以上两个排序语句等价于:
rows_by_fname = sorted(rows, key=lambda r: r['uid'])
rows_by_lfname = sorted(rows, key=lambda r: (r['lname'],r['fname']))
#但使用 itemgetter() 方式会运行的稍微快点

2. itemgetter同样适用于min( )和max( )等函数

rows_min_uid=min(rows, key=itemgetter('uid'))
print(rows_min_uid)
{'uid': 1001, 'lname': 'Cleese', 'fname': 'John'}

OrderedDict 有序字典

1. 为了能控制一个字典中元素的顺序,你可以使用 collections 模块中的 OrderedDict 类。 在迭代操作的时候它会保持元素被插入时的顺序

from collections import OrderedDict

d={}
d[0]=3;d[6]=1;d[3]=1 //仔细看插入顺序
for k,v in d.items():
print(k,v) //输出的时候dict字典会按照key顺序来排序
0 3
3 1
6 1 od=OrderedDict()
od[0]=3;od[6]=1;od[3]=1 //但同样的插入顺序下
for k,v in od.items():
print(k,v) //OrdereDict会保持插入顺序
0 3
6 1
3 1

2. 需要注意的是,一个 OrderedDict 的大小是一个普通字典的两倍,因为它内部维护着另外一个链表,要注意内存消耗问题

[PY3]——字典排序问题总结—(zip()函数、OrderedDict、itemgetter函数)的更多相关文章

  1. python之itemgetter函数:对字典列表进行多键排序

    itemgetter函数:对字典列表进行多键排序 from operator import itemgetter list_people = [ {'name': 'Mike', 'age': 22, ...

  2. Python: 字典列表: itemgetter 函数: 根据某个或某几个字典字段来排序列表

    问题:根据某个或某几个字典字段来排序Python列表 answer: 通过使用operator 模块的itemgetter 函数,可以非常容易的排序这样的数据结构 eg: rows = [ {'fna ...

  3. python中的operator.itemgetter函数

    operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号.看下面的例子 a = [,,] >>> b=) ...

  4. map函数和filter函数 zip函数

    1.map函数 接收一个函数f和一个可迭代对象(列表,字典等),并通过把函数f依次作用在li每个元素上,得到一个新的list并返回 # -*-coding:utf8 -*- import reques ...

  5. python之zip函数和sorted函数

    # zip()函数和sorted()函数 # zip()函数:将两个序列合并,返回zip对象,可强制转换为列表或字典 # sorted()函数:对序列进行排序,返回一个排序后的新列表,原数据不改变 # ...

  6. Python中的sorted函数以及operator.itemgetter函数 【转载】

    operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1,2 ...

  7. Python中的sorted函数以及operator.itemgetter函数

    operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1,2 ...

  8. python--sorted函数和operator.itemgetter函数

    1.operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1 ...

  9. 关于python中的operator.itemgetter()函数的用法

    1. operator.itemgetter(num)函数 表示对对象的第num维数据进行操作获取. >>>import operator >>>a = [1, 2 ...

随机推荐

  1. 关于SVN浏览服务器的错误

    这种错误是因为URL错误,需要把https://iZ1gyqtig7Z/svn/BoLeBang/   换成自己的公网ip地址 https://xx.xx.xx.xxsvn/BoLeBang/ 就可以 ...

  2. django 快捷代码提示

    1.右键项目,Mark Directory As Source Root 2.settings配置 3.import包时可忽略app名了

  3. 【题解】 UOJ #2. 【NOI2014】起床困难综合症

    传送门 不是很简单? 考虑一下这个数的二进制位是什么,要么是1,要么是0. 然后怎么做? 因为一开始可以选0~m的数,那么二进制为中全是0的肯定是可以选的. 接着考虑全是1的怎么选? 如果全都是1的而 ...

  4. 932. Beautiful Array

    For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such ...

  5. OCP 12c最新考试题库及答案(071-2)

    2019-02-12 16:23:54   2.(4-7) choose the best answer:You need to display the first names of all cust ...

  6. 最后一个 last-of-type

    last-of-type这个比较好点,有时候:last-child 不起作用

  7. 使用beautifulsoup和pyquery爬小说

    # -*- coding:UTF-8 -*- from bs4 import BeautifulSoup #BeautifulSoup就是处理字符串的工具 import requests, sys & ...

  8. Ionic开发Hybrid App问题总结

    http://ionichina.com/topic/5641b891b903cba630e25f10 http://www.cnblogs.com/parry/p/issues_about_buil ...

  9. P3994 高速公路

    题目链接 题意分析 这是一道树上斜率优化题 首先 \[dp[i]=min\{dp[j]+(dis[i]-dis[j])* p[i]+q[i]\}(j∈Pre_i)\] 那么就是 \[p[i]=\fra ...

  10. Maven环境下面多项目之间的引用

    如图: https://github.com/sdl/odata-example  sdl OData例子包含了4个项目,下载到本地后编译.发现只有model项目是可以编译过去了.其他几个暂时编译不过 ...