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 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. If there is a match, I would like to know the positionId and the subListCreator underneath it. An item can only have one commentId, hence the [0] in the code.
It would also be ok to just have the whole dictionary "branch" that matches the commentId, this would also make things work.
Btw, print(commentid)
gives me the commentid I would like to match against. 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:
for sublist in list['sublist']:
for item in sublist['item']:
if item['commentId'] == commentid:
number = item['positionId']
username = sublist['subListCreator']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.