gpt4 book ai didi

Python高效过滤dict的方法

转载 作者:行者123 更新时间:2023-12-01 03:01:52 24 4
gpt4 key购买 nike

我有一个非常简单(但非常大)的 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 的内容,但我还不知道如何使用它,也不知道它是否是一个好主意。

最佳答案

只是:

dict_out = {k: {f: v[f] for f in allowed_fields if v.get(f)} 
for k, v in dict_in.items()}

注意:

如果您仍在使用 python 2.7,请使用 .iteritems() 而不是 .items()

关于Python高效过滤dict的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43727897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com