我有一个清单
lis = [{'score': 12, 'name': 'random_content', 'numrep': 11}, {'score': 31, 'name': 'some_content', 'numrep': 10}]
如何读取此列表中特定键的值?即名称的分值:上面列表中的“some_content”,等于 31。
我有一个清单
lis = [{'score': 12, 'name': 'random_content', 'numrep': 11}, {'score': 31, 'name': 'some_content', 'numrep': 10}]
如何读取此列表中特定键的值?即名称的分值:上面列表中的“some_content”,等于 31。
最好在dict
此处使用 a 来快速查找任何'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
使用列表综合,生成器表达式:
>>> [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'