0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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'].

3 Comments

Thanks for your response but if I try to use the following code as you suggested I still get the same type error. To be more specific, I am trying to access the objects stored under 'scans' key in each element of list 'peaks'.
I got that. What are the actual yaml file contains that is my concern. Thanks! The format of dict is not clear to me.
The actual yaml file contains a dict of two lists. 'peaks' is one of the two lists which has further nested elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.