字典列表 - 如何读取字典中的特定值

时间:2013-08-12 12:02:42

标签: python

我有一个清单

lis = [{'score': 12, 'name': 'random_content', 'numrep': 11}, {'score': 31, 'name': 'some_content', 'numrep': 10}]

如何读取此列表中特定键的值? 即名称的得分值:上面列表中的'some_content'等于31。

2 个答案:

答案 0 :(得分:2)

最好在此使用dict来快速查找任何'name'

from collections import defaultdict
lis = [{'score': 12, 'name': 'random_content', 'numrep': 11}, {'score': 31, 'name': 'some_content', 'numrep': 10}]
dic = defaultdict(dict)
for d in lis:
    for k,v in ((k,v) for k,v in d.iteritems() if k != 'name'):
        dic[d['name']][k] = v

现在dic看起来像:

defaultdict(<type 'dict'>,
{'random_content': {'score': 12, 'numrep': 11},
 'some_content': {'score': 31, 'numrep': 10}
})

'some_content'时间内获取O(1)的分数:

>>> dic['some_content']['score']
31

答案 1 :(得分:1)

使用列表理解,生成器表达式:

>>> [x for x in lis if x['name'] == 'some_content']
[{'score': 31, 'name': 'some_content', 'numrep': 10}]
>>> [x['score'] for x in lis if x['name'] == 'some_content']
[31]
>>> next(x['score'] for x in lis if x['name'] == 'some_content')
31

>>> next(x['score'] for x in lis if x['name'] == 'ome_content')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next((x['score'] for x in lis if x['name'] == 'no-such-content'), 'fallback')
'fallback'