kkhatri99
kkhatri99

Reputation: 916

Accessing objects in lists nested in dicts. Python

I have a list of dicts coming from a yaml file. Each dict has nested lists of dicts that I can read as below:

import yaml

stream = open('KK_20130701_003_19844.yaml','r')
data = []
data.append(yaml.load(stream))
for rows in data:
    print rows['peaks']




{'peaks': 
    [{'intensity': [1217.956975, 1649.030477, 7081.000197,... 15225.865077, 15230.394569, 20125.554444], 
    'z': [1, 1, 1, ... 24, 24, 24], 
    'scans': [{'z': 0.0, 'id': 19844, 'mz': 0.0}]}], 
    'scan': [{'z': 0.0, 'id': 19844, 'mz': 0.0}]
}

I am not sure what the best way is to each of the elements in the nested lists and the nested dicts in the lists. If I try to read them as dicts i get the following typeerror: TypeError: list indices must be integers, not str

Upvotes: 0

Views: 162

Answers (2)

Sharif Mamun
Sharif Mamun

Reputation: 3554

There is only one value for ['peaks'], instead of writing a loop simply write this:

print data['peaks']

You can run loop on data['peaks'].

Upvotes: 3

Chris Johnson
Chris Johnson

Reputation: 21956

This is a nested structure. You need to reference each layer according to the type of that layer, accessing the dicts as dicts and lists as lists. So for example, if the overall dict you show above is called x, then the id element is accessed as:

x['peaks'][0]['scan'][0]['id']

It's easiest to understand & debug structures like this by drilling through layers -- first review x['peaks'], then once you understand that move down to x['peaks'][0], and so on.

Upvotes: 4

Related Questions