-1

I have this data set:

print(resp)

{'entityId': 'Vcenter-123', 
'displayName': 'testVCenter', 
'firstSeenTms': 1584129386246, 
'lastSeenTms': 1625163328453, 
'properties': {'virtualizationSupervisor': 'VMWARE_VCENTER', 'detectedName': 'testVCenter', 'vcenterHostNumber': 60, 'vcenterVmNumber': 1612, 'vcenterInfo': '[vendor: VMware, Inc., version: 6.5.0, host: testVCenter]'}, 
'tags': [], 
'managementZones': [{'id': '0001234', 'name': 'test123'}], 
'icon': {'primaryIconType': 'vcenter'}, 'fromRelationships': {'manages': [{'id': 'HYPERVISOR-123', 'type': 'HYPERVISOR'}, {'id': 'HYPERVISOR-345', 'type': 'HYPERVISOR'},{'id': 'HYPERVISOR-456', 'type': 'HYPERVISOR'}]}}

I need to build an array where anything type='HYPERVISOR'. For example, on this data set array needs to be like this:

 hypervisorsName=['HYPERVISOR-123','HYPERVISOR-345','HYPERVISOR-456']

this json file is type dict

I am trying this:

hypervisorsName=resp['fromRelationships']['manages']['id']

I get this error:

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

Is there an easy way to do this?

3
  • 1
    Yes, of course. Use integers to index lists, not strings. In case you aren't aware, resp['fromRelationships']['manages'] is a list. Commented Jul 1, 2021 at 20:07
  • This should answer your question: Getting a list of values from a list of dicts Commented Jul 1, 2021 at 20:15
  • You can also use pandas json normalizer pd.json_normalize(resp['fromRelationships']['manages']) Then you can list the column you want. list( pd.json_normalize(resp['fromRelationships']['manages'])['id']) Output: ['HYPERVISOR-123', 'HYPERVISOR-345', 'HYPERVISOR-456'] Commented Jul 1, 2021 at 20:30

1 Answer 1

1

resp['fromRelationships']['manages'] is a list. You need to iterate over items in the list and get item['id']. You can use list comprehension like this:

hypervisorsName = [item.get('id')
                   for item in resp['fromRelationships']['manages']
                   if item.get('type') == 'HYPERVISOR']
Sign up to request clarification or add additional context in comments.

1 Comment

While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.