Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get max,avg in collections dict(list) in python

I have collections.defaultdict(list) created using collections library.

bids = collections.defaultdict(list)

this inside some for loop iterates and generates the dict (list)

defaultdict(<class 'list'>, {'BTCUSDTbid': [Decimal('0.6769610531551781143397029809')], 'BNBUSDTbid': [Decimal('0.5522217722637411184331627582'), Decimal('1.656726308813783962889330683'), Decimal('0.3682020692956294414374608785')]}) 

Now i need for all keys, the max value and average value. I searched and couldnt able to get answers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use some dict comprehensions:

maxes = {key: max(arr) for key, arr in bids.items()}
averages = {key: sum(arr)/len(arr) for key, arr in bids.items()}

# Use like this: print(maxes['BTCUSDTbid'], averages['BTCUSDTbid'])

Let me know if there’s something there that you don’t understand

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading