Home > Back-end >  How to get max,avg in collections dict(list) in python
How to get max,avg in collections dict(list) in python

Time:12-24

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.

CodePudding user response:

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

  • Related