Home > Net >  How to add .json to List or dictionary for sorting
How to add .json to List or dictionary for sorting

Time:05-03

So i'm getting data from websocket connection.Like this.

{"provider":"cryptocom","from":"BCH","rate":281.951036,"to":"USDT"}
{"provider":"gemini","from":"DOGE","rate":0.13055346,"to":"USDT"}
{"provider":"hitbtc","from":"BCH","rate":282.7334121,"to":"USDT"}
{"provider":"exmo","from":"BCH","rate":280.98464349,"to":"USDT"}
{"provider":"bitfinex","from":"ZEC","rate":120.568875,"to":"USDT"}
{"provider":"bitstamp","from":"BTC","rate":37692.36549,"to":"USD"}

I want to sort them for example: get every ("from":"BCH") and get lowest and highest rate something like this:

BCH - Highest- 282.7334121 Provider - cryptocom  <--> Lowest-280.98464349 provider- exmo 
Doge - Highest- 0.13055346 Provider - gemini  <--> Lowest-0.12055346 provider- cryptocom
....

So i'm looking for way to do that in python but i'm not sure how to get from point a to b :D ,

CodePudding user response:

You could use itertools.groupby after putting all the data into a list:

from itertools import groupby


def main() -> None:
    data = [
        {"provider":"cryptocom","from":"BCH","rate":281.951036,"to":"USDT"},
        {"provider":"gemini","from":"DOGE","rate":0.13055346,"to":"USDT"},
        {"provider":"hitbtc","from":"BCH","rate":282.7334121,"to":"USDT"},
        {"provider":"exmo","from":"BCH","rate":280.98464349,"to":"USDT"},
        {"provider":"bitfinex","from":"ZEC","rate":120.568875,"to":"USDT"},
        {"provider":"bitstamp","from":"BTC","rate":37692.36549,"to":"USD"},
    ]
    for coin, group in groupby(sorted(data, key=lambda d: d['from']),
                               key=lambda d: d['from']):
        sorted_group = sorted(group, key=lambda d: d['rate'])
        highest, lowest = sorted_group[-1], sorted_group[0]
        print(
            f'{coin} '
            f'- Highest - {highest["rate"]} Provider - {highest["provider"]} '
            '<--> '
            f'- Lowest - {lowest["rate"]} Provider - {lowest["provider"]}')


if __name__ == '__main__':
    main()

Output:

BCH - Highest - 282.7334121 Provider - hitbtc <--> - Lowest - 280.98464349 Provider - exmo
BTC - Highest - 37692.36549 Provider - bitstamp <--> - Lowest - 37692.36549 Provider - bitstamp
DOGE - Highest - 0.13055346 Provider - gemini <--> - Lowest - 0.13055346 Provider - gemini
ZEC - Highest - 120.568875 Provider - bitfinex <--> - Lowest - 120.568875 Provider - bitfinex
  • Related