简体   繁体   English

访问嵌套在字典中的列表中的对象。 蟒蛇

[英]Accessing objects in lists nested in dicts. Python

I have a list of dicts coming from a yaml file. 我有一个来自yaml文件的字典列表。 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. 我不确定嵌套列表中的每个元素和列表中的dict是什么最好的方法。 If I try to read them as dicts i get the following typeerror: TypeError: list indices must be integers, not str 如果我尝试将它们作为dict读取,则会出现以下类型错误:TypeError:列表索引必须为整数,而不是str

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. 您需要根据该层的类型引用每个层,以dict的形式访问dict,以列表的形式访问列表。 So for example, if the overall dict you show above is called x , then the id element is accessed as: 因此,例如,如果您在上方显示的整体字典称为x ,则id元素的访问方式为:

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. 通过钻取图层来理解和调试这样的结构是最容易的-首先查看x['peaks'] ,然后一旦您了解到向下移到x['peaks'][0] ,依此类推。

There is only one value for ['peaks'], instead of writing a loop simply write this: ['peaks]只有一个值,而不是编写循环,只需编写以下代码:

print data['peaks']

You can run loop on data['peaks']. 您可以对data ['peaks']运行循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM