Python Forum
For Lopop Python3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: For Lopop Python3 (/thread-36532.html)



For Lopop Python3 - ogautier - Mar-02-2022

Quote:I am trying to obtain the asset and its value from the result without the curly braces, I have tried to do it through various ways and I have not succeeded, could someone help me please?

The result I want to get is ASSET: bitcoin 43935

from pycoingecko import CoinGeckoAPI
import requests
import json
import urllib



base_url = 'https://api.coingecko.com/api/v3/'
    
url = base_url + '/coins'
r = requests.get(url)
identifiers = r.json()
#print(identifiers)
symbol_id_map = {d['symbol']:d['id'] for d in identifiers}
#print(symbol_id_map)
symbols = ['BTC', 'ETH','USDT' ]
ids = [symbol_id_map[symbol.lower()] for symbol in symbols]
ids = ",".join(ids)
url = base_url + f'/simple/price?ids={ids}&vs_currencies=usd'
r = requests.get(url)
print(r.json())
print(type(r))
obj = r.json()
print(type(obj))
print(obj)
    
for key in sorted(obj):
    print("ASSET:",key, ':', obj[key])
Output:
{'bitcoin': {'usd': 43935}, 'ethereum': {'usd': 2923.98}, 'tether': {'usd': 0.999972}} <class 'requests.models.Response'> <class 'dict'> {'bitcoin': {'usd': 43935}, 'ethereum': {'usd': 2923.98}, 'tether': {'usd': 0.999972}} ASSET: bitcoin : {'usd': 43935} ASSET: ethereum : {'usd': 2923.98} ASSET: tether : {'usd': 0.999972}



RE: For Lopop Python3 - bowlofred - Mar-02-2022

Instead of
for key in sorted(obj):
    print("ASSET:",key, ':', obj[key])
Try:
for currency in sorted(obj):
    print(f"ASSET: {currency} {obj[currency]['usd']}")



RE: For Lopop Python3 - tomtom - Mar-02-2022

You can also use this
r = requests.get(url).text
obj = json.loads(r)
 
for key in (obj):
    print(f"ASSET:{key}. 'Value in USD: {obj[key].get('usd')}")