After a mongodb request, I get a document like this:
a = [{"name": 'Aspirin', "Dates": [{'Qty': 50, 'Date':'2019-07-09'}, {'Qty': 10, 'Date': '2020-05-19'}]}]
I would like to retrieve the quantity 50 related to the date 2019-07-09. This is how I proceed:
old_qte = None
for i in a:
for key, value in i.items():
if value == 'Aspirin':
for k, v in i.items():
if k == 'Dates':
for z in v:
for x, y in z.items():
if y == '2019-07-09':
old_qte = z
print(old_qte['Qty'], old_qte)
It works very well but it seems very convoluted. Will someone have a simpler and more readable approach?
This will get you there in one line:
next(date for date in a[0]['Dates'] if date['Date'] == '2019-07-09')['Qty']
#50
Will fetch only the first one that satisfies condition and take Qty from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With