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

2024-03-29 13:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

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

如何读取此列表中特定键的值? i、 e.名称的得分值:上面列表中的“某些内容”,等于31。你知道吗


Tags: name名称内容列表randomsomecontent单子
2条回答

使用列表压缩,生成器表达式:

>>> [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'

最好在这里使用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}
})

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

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

相关问题 更多 >