【问题标题】:Best way to add dictionary entry and append to JSON file in Python在 Python 中添加字典条目并附加到 JSON 文件的最佳方法
【发布时间】:2018-05-30 17:48:58
【问题描述】:

我需要使用以下键将条目添加到字典中:

name
element
type

我希望每个条目都附加到一个 JSON 文件中,我将在其中访问它们以用于项目的另一部分。

我在下面的内容在技术上是可行的,但是这有几件事(至少)有问题。

首先,它不会阻止输入重复项。例如,我可以让“xyz”、“4444”和“test2”多次显示为 JSON 条目。有没有办法纠正这个问题?

有没有一种更简洁的方法来编写实际的数据条目,所以当我将这些值输入字典时,它不会直接出现在括号中?

最后,有没有更好的地方来放置 JSON 片段?它应该在函数内部吗?

只是想稍微清理一下。谢谢

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')

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    这里有几个问题。值得一提的要点:

    • 使用可以使用list 来保存您的参数,并在您将它们提供给add_entry 时使用*args 解包。
    • 要检查/避免重复,您可以使用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
    

    结果:

    print(res)
    
    [{'name': 'xyz', 'element': '4444', 'type': 'test2'},
     {'name': 'wxy', 'element': '3241', 'type': 'test3'}]
    

    通过函数写入 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')
    

    【讨论】:

    • 这很有帮助,感谢您花时间解释它并为我编写解决方案。看起来 List/Set 是这里的关键,而不是使用字典。再次感谢
    • 快速问题....我执行了您的脚本并且它按预期工作,但是当我完全按原样再次执行它时,它会将相同的 2 条记录附加到 .json 文件中。我在 set() 功能中的某个地方发现它会阻止这种情况。也许是因为那只在那个特定的运行实例期间才有效?我猜只是我需要注意的事情。
    • @JD2775,是的,您应该小心重新启动内核(如果在 Jupyter 笔记本中运行)以确保您的变量不会过时;或确保通过res = []重置您的结果列表。
    【解决方案2】:

    你可以试试这个方法

    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))
    

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2015-03-21
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多