用Python永久存储字典的优雅方式? [英] Elegant way to store dictionary permanently with Python?

查看:153
本文介绍了用Python永久存储字典的优雅方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前昂贵地解析一个文件,生成一个约400个键,值对的字典,很少更新。以前有一个函数解析文件,将其写入字典语法中的文本文件(即 dict = {'Adam':'Room 430','Bob':'Room 404'} )等,并将其复制并粘贴到另一个函数,其唯一的目的是返回解析的字典。

Currently expensively parsing a file, which generates a dictionary of ~400 key, value pairs, which is seldomly updated. Previously had a function which parsed the file, wrote it to a text file in dictionary syntax (ie. dict = {'Adam': 'Room 430', 'Bob': 'Room 404'}) etc, and copied and pasted it into another function whose sole purpose was to return that parsed dictionary.

因此,在每个文件中,我将使用该字典,我将导入该函数,并将其分配给一个变量,现在是字典。想知道是否有一个更优雅的方式来做到这一点,这不涉及显式复制和粘贴代码?使用数据库类似乎不必要,并且文本文件给了我看看解析是否正确地完成之前添加到函数的好处。

Hence, in every file where I would use that dictionary, I would import that function, and assign it to a variable, which is now that dictionary. Wondering if there's a more elegant way to do this, which does not involve explicitly copying and pasting code around? Using a database kind of seems unnecessary, and the text file gave me the benefit of seeing whether the parsing was done correctly before adding it to the function. But I'm open to suggestions.

推荐答案

为什么不把它转储到一个JSON文件,然后从那里加载它需要它吗?

Why not dump it to a JSON file, and then load it from there where you need it?

import json

with open('my_dict.json', 'w') as f:
    json.dump(my_dict, f)

# elsewhere...

with open('my_dict.json') as f:
    my_dict = json.load(f)

从JSON加载是相当高效的。

Loading from JSON is fairly efficient.

另一种选择是使用 pickle ,但不同于JSON,它生成的文件不是人类可读的,所以你失去了从你的旧方法喜欢的视觉验证。

Another option would be to use pickle, but unlike JSON, the files it generates aren't human-readable so you lose out on the visual verification you liked from your old method.

这篇关于用Python永久存储字典的优雅方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆