在lis中检索词典

2024-05-16 19:55:40 发布

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

我在列表中查找词典时遇到了一些困难。你知道吗

我有一个列表如下:

mylist[0]

{'_id': ObjectId('aleatoryID'),
 'created_at': datetime.datetime(2018, 3, 22, 11, 58, 23, 585000),
 'person': {'id': '00115500',
  'scores': {'SCORE_3': {'@score': '45'}, 'SCORE_1': 205, 'SCORE_2': 487}}}

通过评分1和评分2可以,我的问题是评分3,因为它包含一个子结构。 以下是我的尝试:

persons = []
for document in mylist:
    persons.append((document['person'].get('id'),
                    document['created_at'],
                    document['person']['scores'].get('SCORE_1'),
                    document['person']['scores'].get('SCORE_2'),
                    document['person']['scores']['SCORE_3'].get('@score')
                   ))

KeyError: 'SCORE_3'

在这种情况下,正确的词典编纂方法是什么?你知道吗


Tags: id列表getdatetime评分documentat词典
2条回答

您的子词典中有些条目不存在。关于如何处理这一问题,有多种方法,请选择最适合您需要的方法:

# base case
for document in mylist:
    persons.append((document['person'].get('id'),
                    document['created_at'],
                    document['person']['scores'].get('SCORE_1'),
                    document['person']['scores'].get('SCORE_2'),
                    # the line below causes the trouble
                    document['person']['scores']['SCORE_3'].get('@score') 
                   ))

#1包含默认值

# a tad more tricky than just calling `get`, since you want to work with the
# potential result. Substitute the `None` with the default value of your choice
... document['person']['scores'].get('SCORE_3', {}).get('@score', None)

#2跳过此类案例

try:
    persons.append((document['person'].get('id'),
                    document['created_at'],
                    document['person']['scores']['SCORE_1'],
                    document['person']['scores']['SCORE_2'],
                    document['person']['scores']['SCORE_3']['@score'])
                   ))
except KeyError:
    pass

#3不要跳过这个案子,只跳过这个领域

# couldn't find a way that didn't include 5 `try...except`s or doing approach #1 
# and then filtering `None`s with [x for x in #1 if x is not None]. So I guess 
# default values > skipping fields.

根据你的例子,这应该是可行的:

document['person']['scores'].get('SCORE_3')['@score']

或者只是索引而不使用get

document['person']['scores']['SCORE_3']['@score']

相关问题 更多 >