gpt4 book ai didi

python - 在列表中迭代字典

转载 作者:行者123 更新时间:2023-12-01 01:53:06 24 4
gpt4 key购买 nike

我在列表中迭代字典时遇到一些问题。

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

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

迭代 SCORE_1 和 SCORE_2 没问题,我的问题是 SCORE_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'

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

最佳答案

您的子词典中有一些不存在的条目。有多种方法可以解决此问题,请选择最适合您需求的一种:

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

关于python - 在列表中迭代字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50530289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com