Skip to main content
 首页 » 编程设计

python之将 dicts 从 csv 复制到新的 dict-python

2024年11月01日10zdz8207

我正在使用一个解析器,它从一个文本文件中读取数据并像这样返回字典:

{'m/z array': array([  345.1,   370.2,   460.2,  1673.3,  1674. ,  1675.3]), 
'charge array': array([ 3,  2,  1,  1,  1,  1]), 
'params': {'username': 'Lou Scene', 'useremail': 'leu@altered-state.edu', 
'mods': 'Carbamidomethyl (C)', 'itolu': 'Da', 'title': 'Spectrum 2', 
'rtinseconds': '25', 'itol': '1', 'charge':`enter code here` '2+ and 3+', 
'mass': 'Monoisotopic', 'it_mods': 'Oxidation (M)', 
'pepmass': (1084.9, 1234.0), 
'com': 'Based on http://www.matrixscience.com/help/data_file_help.html', 
'scans': '3'}, 
'intensity array': array([  237.,   128.,   108.,  1007.,   974.,    79.])} 

我正在尝试读取整个文件(所有的字典)并将它们存储在一个对象中以传递给第二个函数,这样脚本就不必每次都从文件中读取(这非常慢)。我想保留数据的原始结构,同时传递它以便于访问。做这个的最好方式是什么?

我尝试使用以下代码:

print ('enter mgf file name') 
mgf_file = str(raw_input()) 
from pyteomics import mgf 
reader = [] 
with mgf.read(mgf_file) as temp_read: 
    for things in temp_read: 
        reader.update(things) 
 
 
compo_reader(reader) 

请您参考如下方法:

只需将它们放在一个列表中并传递列表即可。

由于您没有向我们展示您的代码,我无法向您展示如何更改它,但我可以向您展示一些伪代码。

假设您有一个函数 parser(f),它从 f 中读取一行并返回您向我们展示的那些字典之一,或者 None 当它完成时。所以:

with open(filename, 'rb') as f: 
    things = [] 
    while True: 
        thing = parser(f) 
        if not thing: 
            break 
        things.append(thing) 

或者,更简洁:

with open(filename, 'rb') as f: 
    things = list(iter(partial(parser, f), None)) 

如果您使用的解析器已经是可迭代的,例如 csv.DictReader,那么它就更简单了:

with open(filename, 'rb') as f: 
    reader = csv.DictReader(f) 
    things = list(reader) 

无论您采用何种方式,一旦您拥有了这些字典的列表,您就可以传递该列表、对其进行迭代等。


对于您的特定代码,它看起来像一个 mgf.read() 对象是字典的迭代器,就像一个 csv.DictReader,所以它应该只是:

with mgf.read(mgf_file) as temp_read: 
    reader = list(temp_read) 

如果那不是真的,你会想这样做:

reader = [] 
with mgf.read(mgf_file) as temp_read: 
    for thing in temp_read: 
        reader.append(thing) 

换句话说,不是用每个新的字典在字典上重复调用 update,而是将每个字典append 到一个列表中。