Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Retrieving items from JSON
#1
Hi,

I am very new to Python and I apologise if I am asking this wrong. I have retrieved a list of tenants via the API I am trying to use. I need to retrieve the ID, Name and Region from the result. I have 10 tenants.

I managed to do this earlier in my code, but that didn't returned any items, just a set of tokens that were easy to retrieve. How do I get just the tokens I want from this list? Below is my code

r = requests.get(tenants_url, headers=headers)
tenants = r.json()
If I look in the debugger I get this

<class 'dict'>: {'items': [{'id': '0e717975-4dce-b911-23276700d154', 'name': 'UK', 'dataGeography': 'IE', 'dataRegion': '01', 'billingType': 'trial', 'partner': {'id': '31e6dc97-4239-a6c5-2faae47b111a'}, 'organization': {'id': '045796c3-a448-b93c77d6b0d2'}, 'apiHost': 'https://api.com'}, {'id': '1e0f069e-458d-954b-353500717c20', 'name': 'US', 'dataGeography': 'IE', 'dataRegion': '02', 'billingType': 'trial', 'partner': {'id': '31e6dc97-3907-a6c5-2faae47b111a'}, 'organization': {'id': '045796c3-a448-b93c77d6b0d2'}, 'apiHost': 'https://api.com'},
This is repeated for each tenant.

Any help would be much appreciated.

Best wishes

Michael
Reply
#2
for tenant in tenants["items"]:
    tenant_id = tenant["id"]
    tenant_name = tenant["name"]
    tenant_region = tenant["dataRegion"]
    print(', '.join([tenant_id, tenant_name, tenant_region]))
Output:
0e717975-4dce-b911-23276700d154, UK, 01 1e0f069e-458d-954b-353500717c20, US, 02
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks Buran. I will try that in the morning. I appreciate the quick reply.
Reply
#4
Thank you. That worked a treat. I am now trying to get those results in to a Dictionary. Nothing gets added. What did I miss?

tenant_d = {'id': '', 'name': '', 'dataRegion': ''}
for tenant in tenants["items"]:
    tenant_id = tenant["id"]
    tenant_name = tenant["name"]
    tenant_region = tenant["dataRegion"]
    tenant_d['id']: tenant_id
    tenant_d['name']: tenant_name
    tenant_d['dataRegion']: tenant_region
    print(', '.join([tenant_id, tenant_name, tenant_region]))
Reply
#5
starting from your code - you need to assign value to key, e.g.
tenant_d['id'] = tenant_id
or
directly
tenant_id = tenant["id"]
you can also construct dict like
tenant_d = {'id':tenant_id, 'name':tenant_name, 'dataRegion':tenant_region}
All that said - tenant is already a dict (just with more key:value pairs) why do you need to create a different dict? i.e. all these is not necessary
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Thanks buran. I appreciate the quick response once again. I was using this to try and learn some more techniques. I only need those parts so I decided I would keep it cleaner. Later on in the process I will be returning a lot of other information, some of which I won't want, the rest I would want to output to a file.

The only way I learn is by doing. I was happy for my code to be bad, in the two many steps way, get the result I wanted, then go back and make it better. I hope that makes sense.
Reply
#7
in this case here is one more technique
keys = ('id', 'name', 'dataRegion')
for tenant in tenants["items"]:
    tenant_d = {key:value for key, value in tenant.items() if key in keys}
    print(tenant_d)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
That makes perfect sense. Thank you. I may have cracked this hours ago and not realised. Although your way is nicer. I was using PyCharm and checking the debugger. I expected the debugger to return the whole dictionary, but it just returns the last entry. I expected to see the other 9

tenant_d = {dict} <class 'dict'>: {'id': 'fbac1d47-d1d0-4180-a2de-8b3088c4fb35', 'name': 'UK', 'dataRegion': '01'}
'id' (4402128912) = {str} 'fbac1d47-d1d0-4180-a2de-8b3088c4fb35'
'name' (4407218048) = {str} 'UK'
'dataRegion' (4407271792) = {str} 'eu01'
__len__ = {int} 3
Reply
#9
Sorry buran.

For my sanity I have written the below.

keys = ('id', 'name', 'dataRegion')
for tenant in tenants["items"]:
    tenant_d = {key:value for key, value in tenant.items() if key in keys}
    print(tenant_d)

for tenants in tenant_d.items():
    print(tenants)
That returns just one set of tenants item, the last one. It would seem it is not adding items to the dictionary
Reply
#10
note that you can not have multiple identical keys in a dict. At each iteration of the first loop tenant_d is a dict with values for just one tenant. Then you print that dict and continue with next iteration if you look at the original json you will notice that tenants["items"] is actually a list of dicts. You need something like this to store the tenant_d if you want to keep all of them. Again that will replicate the original structure

after you finish the first loop tenant_d has the values for the last item in the list. that is what you iterate over and print in the second loop
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  KeyError while retrieving ESPN data john317ab 2 800 Nov-29-2023, 09:07 PM
Last Post: john317ab
  .get() not retrieving value? Sedos101 2 558 Aug-25-2023, 11:48 AM
Last Post: deanhystad
  [Solved] Retrieving a pdf from sqlite3 BigMan 4 2,298 Mar-12-2022, 01:56 PM
Last Post: deanhystad
  Retrieving a column from a data set using a function Bayle 6 2,325 Oct-06-2021, 08:52 PM
Last Post: Bayle
  Retrieving Cookies whois1230 2 2,164 Nov-21-2020, 12:01 PM
Last Post: snippsat
  Problem: Retrieving Form data PythonDev 3 3,070 Oct-16-2020, 02:09 AM
Last Post: PythonDev
  Retrieving dictionary keys within with another dictionay bazcurtis 8 2,802 Oct-29-2019, 10:06 PM
Last Post: bazcurtis
  Trouble retrieving dictionary from mysql.connector cursor swechsler 2 3,027 Sep-17-2019, 05:21 PM
Last Post: swechsler
  retrieving pvalue from statsmodels results Staph 4 3,012 Jul-18-2019, 03:27 PM
Last Post: Gribouillis
  PRAW and PyQt: Immense slowdown when retrieving Reddit posts and adding them to GUI codebro 2 3,210 Dec-30-2018, 01:19 AM
Last Post: codebro

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020