Home > Enterprise >  Python JSON API Print the list inside of a dictionary
Python JSON API Print the list inside of a dictionary

Time:10-12

I have the following code:

import requests
import re
import json
p={
    'collection': 'wisecards',
    'limit':5
    }

g=requests.get("https://api.opensea.io/api/v1/assets?offset=0",params=p)
x=(g.json())
price=[d['sell_orders']['current_price'] for d in x['assets']]
print(price)

and I get this error:

price=[d['sell_orders']['current_price'] for d in x['assets']]
TypeError: list indices must be integers or slices, not str

The JSON data is here: https://paste.pythondiscord.com/izeresurub.py

How can I print the list inside this dictionary?

Using price=[d['sell_orders'] for d in x['assets']] print the whole list,but i want just a specific part of it ['current_price']

CodePudding user response:

The element in the JSON seems to be a list, so iterating over it will yield the items themselves but here ya go

import requests
import re
import json
p={
    'collection': 'wisecards',
    'limit':5
    }
g = requests.get("https://api.opensea.io/api/v1/assets?offset=0", params=p).json()
for d in g['assets'][1]['sell_orders']:
    price = d['current_price']
print(price)

CodePudding user response:

x['assets'] is a list of length 1 that contains a dict.

x['assets'][0] accesses the dict within that list.

x['assets'][0]['sell_orders'] yields yet another list that contains 1 dict

x['assets'][0]['sell_orders'][0] accesses the dict in that list (length 42 - all attributes of the sell order)

x['assets'][0]['sell_orders'][0]['current_price] gets you what you want.

In the future for troubleshooting, try checking what the type of everything is and using dir(object) to check object's attributes

  • Related