【发布时间】:2017-09-29 09:18:03
【问题描述】:
我有一个非常简单(但非常大)的 JSON 文件,我需要对其进行一些过滤。 (我已经有一段时间没有做任何python了......)
看起来像这样:
{
'entry_1': {
'field_1' : 'value',
'field_2' : 123,
'field_3' : '',
'field_4' : 456
},
'entry_2': {
'field_1' : 'value',
'field_2' : 321,
'field_3' : 'value',
'field_4' : 654
},
...
}
我想过滤它以删除无用的字段。我的测试文件很小,我做的很好,但我需要在一个相当大的文件上做,而且我知道我的代码很丑。
到目前为止,我已经这样做了:
dict_in = json.load(INFILE)
dict_out = defaultdict(dict) #4harambe
allowed_fields = {'field_1', 'field_3'}
'''should I use a set or a tuple here ? or maybe something else
All data inside will be unique (set) but
those data wont change (tuple)
'''
for entry in dict_in:
for field in dict_in[entry]:
if field in allowed_fields and not dict_in[entry][field]:
# allowed field plus non empty string
dict_out[entry][field] = dict_in[entry][field]
我想知道如何让它更性感、更高效(双循环 + if 语句以及我访问数据的方式非常糟糕)。我已经阅读过 itertools,但我还不知道如何使用它以及它是否是个好主意。
【问题讨论】:
-
将其保留为
set()O(1) 与元组 O(n)。此外,从下面的答案来看,你的答案是最易读的,并且性能可能完全相同。
标签: python json performance dictionary filtering