Python Forum

Full Version: Retrieving items from JSON
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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
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
Thanks Buran. I will try that in the morning. I appreciate the quick reply.
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]))
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
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.
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)
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
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
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
Pages: 1 2