TypeError: list indices must be integers or slices, not str in Python

Issue related to: Core Python – Lists, The use of APIs

Libraries used: requests, json

Issue Link: Posted byu/bank2400

Issue:

TypeError: list indices must be integers or slices, not str

I am trying to get the value ”highBid”, from the dictionaries from the list ”results”, into a new list but it’s giving me this error messages. Does someone know how to do this and what I am doing wrong?

import requests, json
url = "https://campenauktioner.hibid.com/api/v1/lot/list/204748?pn=1&ipp=95"
text = requests.get(url).text
data = json.loads(text)
price = []
for results in data['results'],['lotStatus']:
price.append(results['highBid'])

Short Answer

There is a list not a dictionary in “results”

Explanation

The user wants to use an API for an auction site to gather information on the highest bid. He then wants to use this data later in his program.

We will begin by creating a plan of action.

  • Import the API into our program
  • Familiarize our self with the data and find ‘highBid’ for one instance
  • Create a loop to take out all instances of ‘highBid’
  • Create a list to store the information

To begin with, let us import the API into our program. We will use the modules requests to get the webpage and json to deal with information

import requests, json

Next we need to get hold of the api

We will store the url link in a variable which we will appropriately call url.

url = "https://campenauktioner.hibid.com/api/v1/lot/list/204748?pn=1&ipp=95"

We will then use requests module to get the contents of the api which we will call text.

text = requests.get(url).text

Now we need to decode the text we have gotten from the url. We can use use the json.loads on text to make this task easier. We are now able to see the contents of the API therefore we will use the print function.

data = json.loads(text)
print(data)

The next task is to familiarize our self with the data.

Due to the length of the data this can be quite difficult – we need to make the data smaller. To make the data smaller we first need to identify what we are working with.

To do this we can use the function type on data and print the output.

print(type(data))

Output

<class 'dict'>

We can confirm that we are working with a dictionary- Now we need to get hold of the data we want so we will look for where it says highBid.

Currently it is hard to understand the information – we need to make the data more readable we can use the function json.dumps() and pass the parameters data, indent=6 (to add spaces for indentation) and sort_keys=True (to sort keys ascending order) and we will print this out

print(json.dumps(data, indent = 6, sort_keys=True))

We will locate highBid in the output:

 "results": [
{
"altBiddingUrl": "",
"altBiddingUrlCaption": "",
"atAuctionId": 0,
"auctionBeginDate": "3/11/2020",
"auctionCity": "5690",
"auctionEndDate": "4/20/2020",
"auctionState": "DK",
"auctionZip": "Tommerup",
"bidAmountType": 1,
"bidQuantity": "",
"bidType": 3,
"companyId": 61079,
"companyName": "Campen Auktioner A/S",
"currAbbrev": "DKR",
"currencyExpressUrl": "",
"defaultBidAmountToMinBid": true,
"description": "SLUT: Mandag den 20. April kl. 19.00\rEFTERSYN: Fredag den 17. April kl. 13-15\rCampen Auktioner opfordrer vores kunder til 
at komme til eftersyn jvf. \u00a74 i auktionsbetingelserne.\rBETALING: Faktura skal betales med straksoverf\u00f8rsel senest 24 timer efter modtagelse.\rAFHENTNING: mandag den 27. April kl. 9-16 & tirsdag den 28. April kl. 9-16\rADRESSE: \u00d8sterbro 4, 5690 Tommerup (port 17 - se lot 1a for guide)\rHar du sp\u00f8rgsm\u00e5l til auktionen s\u00e5 ring til: 2271 5555\rFakturasp\u00f8rgsm\u00e5l og lign. rettes til auktionskontoret p\u00e5 E-mail: mail@campenauktioner.dk eller p\u00e5 tlf.: 2271 5555.",
"efAuctionId": 0,
"estimate": "",
"eventId": 204748,
"eventItemId": 63163408,
"eventName": "4498 NET: KONKURS SCANWOOD APS DEL 1 (TOMMERUP)",
"featuredPicture": {
"description": "SLUT: Mandag den 20. April kl. 19.00",
"fullSizeLocation": "https://media.sandhills.com/img.axd?id=6003022271&wid=&p=&ext=&w=0&h=0&t=&lp=&c=True&wt=False&sz=Max&rt=0&checksum=CaH6Gfi5IZcMg9xBi2bB5Kos2aI7JrHd",
"height": 0,
"thumbnailLocation": "https://media.sandhills.com/img.axd?id=6003022271&wid=&p=&ext=&w=0&h=0&t=&lp=&c=True&wt=False&sz=Max&rt=0&checksum=CaH6Gfi5IZcMg9xBi2bB5Kos2aI7JrHd&h=200&w=200",
"width": 0
},
"fr8StarUrl": "",
"hideImage": false,
"hideLeadWithDescription": false,
"itemId": 662151,
"lead": "SLUT: Mandag den 20. April kl. 19.00",
"linkTypes": 0,
"lotNumber": "1",
"lotStatus": {
"bidCount": 0,
"bidMax": 0.0,
"bidMaxTotal": 0.0,
"biddingExtended": false,
"buyNow": 0.0,
"buyerBidStatus": 0,
"buyerHighBid": 0.0,
"buyerHighBidTotal": 0.0,
"choiceType": 0,
"highBid": 0.0,

We can see that it is in the key “results“. Now we can get the contents of “results” – We can see that the contents is a list, to simplify the amount of data we need to read we will only use the first index

We will print(data["results"][0]) - results is the key and we are getting the first element in the results list 

Output

{'site': {'siteId': 61079, 'siteType': 0, 'migrationStatus': 4, 'subscriber': True, 'webExpires': '2050-12-31T00:00:00', 'portalEventHeadQuery': None, 'portalEventItemsQuery': '', 'isPrivatePortal': False, 'isOptOutPortal': False, 'isFramed': False, 'isFramedForTesting': False, 'subdomain': 'CAMPENAUKTIONER', 'domain': None}, 'renderType': 0, 'companyName': 'Campen Auktioner A/S', 'eventName': '4498 NET: KONKURS SCANWOOD APS DEL 1 (TOMMERUP)', 'auctionCity': '5690', 'auctionState': 'DK', 'auctionZip': 'Tommerup', 'auctionBeginDate': '3/11/2020', 'auctionEndDate': '4/20/2020', 'description': 'SLUT: Mandag den 20. April kl. 19.00\rEFTERSYN: Fredag den 17. April kl. 13-15\rCampen Auktioner opfordrer vores kunder til at komme til eftersyn jvf. §4 i auktionsbetingelserne.\rBETALING: Faktura skal betales med straksoverførsel senest 24 timer efter modtagelse.\rAFHENTNING: mandag den 27. April kl. 9-16 & tirsdag den 28. April kl. 9-16\rADRESSE: Østerbro 4, 5690 Tommerup (port 17 - se lot 1a for guide)\rHar du spørgsmål til auktionen så ring til: 2271 5555\rFakturaspørgsmål og lign. rettes til auktionskontoret på E-mail: mail@campenauktioner.dk eller på tlf.: 2271 5555.', 'estimate': '', 'noMinimumCaption': '------', 'defaultBidAmountToMinBid': True, 'pictureCount': 1, 'linkTypes': 0, 'altBiddingUrlCaption': '', 'altBiddingUrl': '', 'hideImage': False, 'hideLeadWithDescription': False, 'currencyExpressUrl': '', 'fr8StarUrl': '', 'atAuctionId': 0, 'efAuctionId': 0, 'shippingOffered': False, 'companyId': 61079, 'eventId': 204748, 'eventItemId': 63163408, 'itemId': 662151, 'ringNumber': 0, 'featuredPicture': {'fullSizeLocation': 'https://media.sandhills.com/img.axd?id=6003022271&wid=&p=&ext=&w=0&h=0&t=&lp=&c=True&wt=False&sz=Max&rt=0&checksum=CaH6Gfi5IZcMg9xBi2bB5Kos2aI7JrHd', 'thumbnailLocation': 'https://media.sandhills.com/img.axd?id=6003022271&wid=&p=&ext=&w=0&h=0&t=&lp=&c=True&wt=False&sz=Max&rt=0&checksum=CaH6Gfi5IZcMg9xBi2bB5Kos2aI7JrHd&h=200&w=200', 'description': 'SLUT: Mandag den 20. April kl. 19.00', 'width': 0, 'height': 0}, 'lotNumber': '1', 'lead': 'SLUT: Mandag den 20. April kl. 19.00', 'currAbbrev': 'DKR', 'quantity': 1.0, 'bidQuantity': '', 'bidType': 3, 'bidAmountType': 1, 'lotStatus': {'status': 2, 'choiceType': 0, 'showBidStatus': False, 'bidCount': 0, 'minBid': 50.0, 'highBid': 0.0, 'highBuyerId': '0', 'showReserveStatus': False, 'reserveSatisfied': True, 'timeLeftLead': '', 'timeLeft': '7d 1h 48m ', 'timeLeftSeconds': 611287.94, 'timeLeftWithLimboSeconds': 611288.94, 'timeLeftTitle': 'Internet Bidding closes at: 4/20/2020 1:00:00 PM EST', 'softCloseMinutes': 2.0, 'softCloseSeconds': 0, 'linkedSoftClose': '', 'biddingExtended': False, 'isOnLiveCatalog': False, 'sealed': False, 'buyerBidStatus': 0, 'mayHaveWonStatus': 'Vindende bydere vil blive kontaktet pr. sms og få tilsendt en mail med faktura dagen efter auktionen slutter. Venligst tjek at dit mobilnummer og din mail fremgår korrekt på din byderkonto, så vi kan få fat i dig. Tak fordi du bød hos Campen Auktioner A/S! Vil du have besked om kommende auktioner? Nyhedsbrev: Tilmeld på www.campenauktioner.dk Facebook: Synes godt om vores side på https://www.facebook.com/campen.auktioner/', 'bidMax': 0.0, 'bidMaxTotal': 0.0, 'buyerHighBid': 0.0, 'buyerHighBidTotal': 0.0, 'isWatching': False, 'watchNotes': None, 'isRegistered': False, 'isArchived': False, 'isHidden': False, 'isPublicHidden': False, 'priceRealizedMessage': None, 'quantitySold': 0.0, 'priceRealized': 0.0, 'priceRealizedPerEach': 0.0, 'buyNow': 0.0, 'productStatus': 0, 'productUrl': ''}}

Inside of this list, there is a dictionary – The key interest is ‘lotStatus’. Again we will use a print statement but this time we will add the key ‘lotStatus’

print(data["results"][0]["lotStatus"])

Output

{'status': 2, 'choiceType': 0, 'showBidStatus': False, 'bidCount': 0, 'minBid': 50.0, 'highBid': 0.0, 'highBuyerId': '0', 'showReserveStatus': False, 'reserveSatisfied': True, 'timeLeftLead': '', 'timeLeft': '7d 1h 32m ', 'timeLeftSeconds': 610348.217, 'timeLeftWithLimboSeconds': 610349.217, 'timeLeftTitle': 'Internet Bidding closes at: 4/20/2020 1:00:00 PM EST', 'softCloseMinutes': 2.0, 'softCloseSeconds': 0, 'linkedSoftClose': '', 'biddingExtended': False, 'isOnLiveCatalog': False, 'sealed': False, 'buyerBidStatus': 0, 'mayHaveWonStatus': 'Vindende bydere vil blive kontaktet pr. sms og få tilsendt en mail med faktura dagen efter auktionen slutter. Venligst tjek at dit mobilnummer og din mail fremgår korrekt på din byderkonto, så vi kan få fat i dig. Tak fordi du bød hos Campen Auktioner A/S! Vil du have besked om kommende auktioner? Nyhedsbrev: Tilmeld på www.campenauktioner.dk Facebook: Synes godt om vores side på https://www.facebook.com/campen.auktioner/', 'bidMax': 0.0, 'bidMaxTotal': 0.0, 'buyerHighBid': 0.0, 'buyerHighBidTotal': 0.0, 'isWatching': False, 'watchNotes': None, 'isRegistered': False, 'isArchived': False, 'isHidden': False, 'isPublicHidden': False, 'priceRealizedMessage': None, 'quantitySold': 0.0, 'priceRealized': 0.0, 'priceRealizedPerEach': 0.0, 'buyNow': 0.0, 'productStatus': 0, 'productUrl': ''}

We now have a dictionary- The key interest is ‘highBid‘. We will use a print statement but this time we will add the key ‘highBid‘

print(data["results"][0]["lotStatus"]["highBid"])

Output

0.0

As we know have what we want. We can now begin constructing our loop

The variable that will be changing is the index number of the list i.e

print(data["results"][0]["lotStatus"]["highBid"])
print(data["results"][1]["lotStatus"]["highBid"])
print(data["results"][2]["lotStatus"]["highBid"])

We will use a for loop as we know that a list has a finite number of item.

We want to iterate over the lists in “results”

We also want our counter “i” to count what number of list it is on

Inside of our for loop we will print(data[“results”][i][“lotStatus”][“highBid”])

Our for loop will loop like this:

for i in range(len(data["results"])):
 print(data["results"][0]["lotStatus"]["highBid"])

This should print out a series of numbers

The next stepis place these numbers into a list, we will create a list called price then instead of printing we will use price.append like so:

price = [] 
for i in range(len(data["results"])):
 price.append(data["results"][0]["lotStatus"]["highBid"])
print(price)

This should give us a list of prices as requested