[英]Best way to add dictionary entry and append to JSON file in Python
I have a need to add entries to a dictionary with the following keys: 我需要使用以下键将条目添加到字典中:
name
element
type
I want each entry to append to a JSON file, where I will access them for another piece of the project. 我希望每个条目都附加到JSON文件中,以便在项目的另一部分访问它们。
What I have below technically works, but there are couple things(at least) wrong with this. 我下面的内容在技术上是可行的,但是这至少有几处错误。
First, it doesn't prevent duplicates being entered. 首先,它不会阻止输入重复项。 For example I can have 'xyz', '4444' and 'test2' appear as JSON entries multiple times.
例如,我可以多次将“ xyz”,“ 4444”和“ test2”作为JSON条目出现。 Is there a way to correct this?
有没有办法纠正这个问题?
Is there a cleaner way to write the actual data entry piece so when I am entering these values into the dictionary it's not directly there in the parentheses? 有没有一种更干净的方法来写入实际的数据输入段,以便当我将这些值输入到字典中时,括号中不直接存在这些值?
Finally, is there a better place to put the JSON piece? 最后,还有更好的放置JSON片段的地方吗? Should it be inside the function?
它应该在函数内部吗?
Just trying to clean this up a bit. 只是尝试清理一下。 Thanks
谢谢
import json
element_dict = {}
def add_entry(name, element, type):
element_dict["name"] = name
element_dict["element"] = element
element_dict["type"] = type
return element_dict
#add entry
entry = add_entry('xyz', '4444', 'test2')
#export to JSON
with open('elements.json', 'a', encoding="utf-8") as file:
x = json.dumps(element_dict, indent=4)
file.write(x + '\n')
There are several questions here. 这里有几个问题。 The main points worth mentioning:
值得一提的要点:
list
to hold your arguments and use *args
to unpack when you supply them to add_entry
. add_entry
时,Use可以使用一个list
来保存您的参数,并使用*args
进行解压缩。 set
to track items already added. set
来跟踪已添加的项目。 Putting these aspects together: 将这些方面放在一起:
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
Result: 结果:
print(res)
[{'name': 'xyz', 'element': '4444', 'type': 'test2'},
{'name': 'wxy', 'element': '3241', 'type': 'test3'}]
Writing to JSON via a function: 通过函数写入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')
you can try this way 你可以这样尝试
import json
import hashlib
def add_entry(name, element, type):
return {hashlib.md5(name+element+type).hexdigest(): {"name": name, "element": element, "type": type}}
#add entry
entry = add_entry('xyz', '4444', 'test2')
#Update to JSON
with open('my_file.json', 'r') as f:
json_data = json.load(f)
print json_data.values() # View Previous entries
json_data.update(entry)
with open('elements.json', 'w') as f:
f.write(json.dumps(json_data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.