Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - Nested list/dictionaries iteration

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?

like image 902
Tobin Avatar asked Apr 07 '26 21:04

Tobin


1 Answers

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.

like image 109
zipa Avatar answered Apr 10 '26 10:04

zipa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!