[英]How to use the index in an enumerate for loop with if statement (python)
I have a nested dictionary, of which it is possible to access a value like this:我有一个嵌套字典,其中可以访问这样的值:
print(list['sublist'][0]['item'][0]['commentId'])
However if I create a for loop and would like to use the index like this it gives me a keyerror:但是,如果我创建一个 for 循环并想使用这样的索引,它会给我一个 keyerror:
for index,sublist in enumerate(list['sublist']):
if sublist[index]['item'][0]['commentId'] == commentid:
number = sublist[index]['item'][0]['positionId']
username = sublist[index]['subListCreator']
print(number)
print(username)
The error:错误:
, in send_async_notification
if sublist[index]['item'][0]['commentId'] == commentid:
File "/Users/ ...... /venv/lib/python3.8/site-packages/mongoengine/base/document.py", line 263, in __getitem__
raise KeyError(name)
The whole goal of this exercise is to get two particular values in a nested array based on a deeper nested commentId.本练习的全部目标是根据更深的嵌套 commentId 在嵌套数组中获取两个特定值。 If there is a match, I would like to know the positionId and the subListCreator underneath it.如果有匹配,我想知道它下面的 positionId 和 subListCreator。 An item can only have one commentId, hence the [0] in the code.一个项目只能有一个commentId,因此代码中的[0]。
It would also be ok to just have the whole dictionary "branch" that matches the commentId, this would also make things work.也可以只使用与commentId 匹配的整个字典“分支”,这也可以使事情正常进行。
Btw, print(commentid)
gives me the commentid I would like to match against.顺便说一句, print(commentid)
给了我想要匹配的 commentid。 Just to explain its present.只是为了解释它的现在。
Hope there's a solution here, wonder why it's not working.希望这里有一个解决方案,想知道为什么它不起作用。 Looking forward to any answer!期待任何答案!
Thanks Mathias for commenting: A double for-loop solves my problem:感谢 Mathias 的评论:双 for 循环解决了我的问题:
for sublist in list['sublist']:
for item in sublist['item']:
if item['commentId'] == commentid:
number = item['positionId']
username = sublist['subListCreator']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.