Skip to content
Advertisement

Access attributes in JSON file with python and filter items which attribute matches to specific value

I have JSON file (list.json) as an input:

JavaScript

I am trying to extract all modules (their names) if “Vendor” matches to some criteria, in this case all of the modules with “Vendor”: “comp” should be printed (Module2, Module3).

My code is: import json

JavaScript

When I run this code, I keep getting: string indices must be integers on line if i['Vendor'] == 'comp':

What would be the best approach to do this?

Advertisement

Answer

You are only missing the fact that your dictionnary of module is a nested one. Each module description is a dictionnary itself.

To iterate through your modules (the keys of your dictionnary) you have to use the .keys() or the .items() method. You can then access every inner dictionnaries.

JavaScript

EDIT:

If you want to take the attributes of your different modules you juste have to access them using their key in the inner dictionary. By specifying which attribute of your dictionary you want you can access its value.

swc_list['Module1'] will give you the entire description dictionnary of the first module

JavaScript

swc_list['Module1']['Layer'] will give you only the value associated with the Layer parameter of th first module

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement