我正在使用csv.DictReader()来读取文件。它实际上返回一个字典列表,而不是单个字典。我如何强制它返回单个字典,或者如何合并它返回的字典列表?Python:DictReader返回字典列表?
def agilent_e8361c_pna_read(file_loc):
'''
Load the '.s2p' file in to a dictionary.
'''
with open(file_loc) as f:
# define the fields in the Agilent '.s2p' file
col_names = ["f","s11","arg_s11","s21","arg_s21","s12","arg_s12","s22","arg_s22"]
# read the data into a dictionary
s2p_dicts = csv.DictReader(itertools.ifilter(n_input.is_comment, f), fieldnames=col_names, delimiter=' ')
return s2p_dict
理想情况下,数据将被最初读成一个单一的字典,从来没有需要合并。它是一组数据。这些列属于一起,没有完整集合或连贯的子集是无意义的。如果DictReader不是“pythonically”能够完成这个壮举,我将决定合并词典列表。这不应该是科学家和程序员都想要用数据集所做的不常见的事情。
为什么会返回单个字典?它为输入文件中的每一行返回一个字典,这就是它的意图。 – 2013-03-22 14:21:43
如果你输入的文件只包含* 1 *行,只需选择那一行:'return next(s2p_dict)'。 – 2013-03-22 14:23:32
如果它包含多行,您是如何预期数据将被映射到字典的键? – 2013-03-22 14:24:27