首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字典列表中的词条

字典列表中的词条
EN

Stack Overflow用户
提问于 2013-06-23 18:06:28
回答 1查看 12K关注 0票数 4

有没有一种更快、更"pythonic“的方法来访问与字典列表中的单个键关联的值,而不是遍历它(如here所示)?我正在寻找像listDict[:]['id']这样的东西来获取值列表,但我得到了错误list indices must be integers, not str,尽管listDict[0]['id']工作得很好。

更新-后续问题:如果键的值也是一个列表本身,而我只对获取它的前10个元素感兴趣,该怎么办?

当使用列表理解时,做[dic['id'][:10] for dic in listDict]很容易,但是当使用itemgetter时呢?map(itemgetter('id')[:10], listDict)似乎不起作用。

我在问一种快速访问的方法,因为我有一个巨大的字典列表,我认为我可以获得与numpy数组相同的行为(比如切片只是原始数组的视图)。我想知道python是否有办法利用这样一个事实,即我的列表中的所有字典都具有相同的大小,可以使用快速跨步内存访问和一次复制大块数据,而不需要像列表列表一样进行中间表示。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2013-06-23 18:07:56

不,你不能在这里做切片。您已经遍历了整个列表,并从每个dict中获取条目。

使用列表理解:

代码语言:javascript
复制
[dic['id'] for dic in listDict]

operator.itemgetter

代码语言:javascript
复制
>>> from operator import itemgetter
>>> map(itemgetter('id'), listDict)

时序比较:

代码语言:javascript
复制
>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] *100

>>> %timeit [dic['id'] for dic in listDict]
10000 loops, best of 3: 50.8 us per loop
>>> %timeit map(itemgetter('id'), listDict)
10000 loops, best of 3: 42.7 us per loop

>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]*1000

>>> %timeit [dic['id'] for dic in listDict]
1000 loops, best of 3: 446 us per loop
>>> %timeit map(itemgetter('id'), listDict)
1000 loops, best of 3: 440 us per loop

>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] *10**5

>>> %timeit [dic['id'] for dic in listDict]
10 loops, best of 3: 50.7 ms per loop
>>> %timeit map(itemgetter('id'), listDict)
10 loops, best of 3: 45.6 ms per loop
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17259657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档