这里有几个问题。值得一提的要点:Use可以使用list保存参数,并在将参数提供给add_entry时使用{}进行解包。在
要检查/避免重复,可以使用set跟踪已添加的项。在
对于写入JSON,现在有了一个列表,您可以简单地迭代列表并在末尾写入一个函数。在
将这些方面放在一起:import json
res = []
seen = set()
def add_entry(res, name, element, type):
# check if in seen set
if (name, element, type) in seen:
return res
# add to seen set
seen.add(tuple([name, element, type]))
# append to results list
res.append({'name': name, 'element': element, 'type': type})
return res
args = ['xyz', '4444', 'test2']
res = add_entry(res, *args) # add entry - SUCCESS
res = add_entry(res, *args) # try to add again - FAIL
args2 = ['wxy', '3241', 'test3']
res = add_entry(res, *args2) # add another - SUCCESS
结果:
^{2}$
通过函数写入JSON:def write_to_json(lst, fn):
with open(fn, 'a', encoding='utf-8') as file:
for item in lst:
x = json.dumps(item, indent=4)
file.write(x + '\n')
#export to JSON
write_to_json(res, 'elements.json')