在列表中迭代字典

时间:2018-05-25 13:25:23

标签: python python-3.x

我在列表中的字典中遇到了一些麻烦。

我有一个如下所示的列表:

/Dashboard

通过SCORE_1和SCORE_2进行迭代很好,我的问题是SCORE_3,因为它包含一个子结构。 这是我的尝试:

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}}}

在这种情况下,字典的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

根据您的示例,这应该有效:

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

或者仅使用get进行索引:

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

答案 1 :(得分:1)

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

# 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.