在一个pickle文件中处理两个字典

0 投票
1 回答
2268 浏览
提问于 2025-04-18 17:27

我想把这个说得很清楚,所以我先从我知道的情况开始,这样大家就能明白我想表达的意思。当我只在一个pickle文件里存储一个字典时,我用的方法是这样的,而且效果很好。

#open pickle file
with open("a_pickle_file", 'rb') as input:
  x = pickle.load(input)
#Now update the dict in your pickle file 
a_dict.update(x)

假设对这个字典进行了一些任意的操作,现在我这样保存:

#Save whatever u added to the dict
pickle.dump(open(a_dict,"a_pickle_file"))

接下来,我要说的是我不太确定的情况,而且我找到的资料似乎很少。我想做和上面完全一样的事情,只不过这次我会把两个字典放在一个列表里,然后把这个列表存储到pickle文件中,像这样:

#Two dict
MyFirstDict = { 1: 'a' }
MySecondDict = { 2:'b' }
#Store them in a list
two_dict = [MyFirstDict, MySecondDict]
#save them 
pkl.dump( two_dict, open( "two_dict_pkl_file", "wb" ) )

现在我在一个列表里有两个字典,并且它们已经存储在我的pickle文件中了。那么接下来,怎么才能加载这个pickle文件进行操作呢?加载后,我该如何访问每个字典,以便进行更新和操作?最后,我能否直接使用上面的pkl.dump语句重新保存它?谢谢。

补充说明

所以在大多数情况下,做这个过程基本上是一样的,除了你需要用之前的信息来更新字典的那部分。这是一个包含两个字典的列表在一个pkl文件中的输出:

[{'I': 'D', 'x': 'k', 'k': [datetime.time(11, 52, 3, 514000)]}, {'I': 'D', 'x': 'k', 'D': [datetime.time(11, 52, 3, 514000)]}]

如你所见,它的存储方式有点奇怪,我似乎无法正确地单独访问每个字典进行更新,可能需要一些语法来正确地做到这一点。

1 个回答

1

试试看吧!用 pickle.load() 这个命令,你会看到里面有一个包含两个字典的列表。你可以用几种方法来引用它们,但这是一种常见的做法:

MyFirstDict, MySecondDict = pickle.load(open("two_dict_pkl_file", "rb"))

没错,如果你想覆盖已有的内容,可以直接用 pickle.dump() 再次保存它们。

编辑

这里有一个脚本来说明这个概念:

import pickle, datetime

test_file = "two_dict_pkl_file"

# store two dicts in a list
MyFirstDict = { 1: 'a' }
MySecondDict = { 2:'b' }
two_dict = [MyFirstDict, MySecondDict]

print "first pickle test"
print "this python list gets pickled:"
print two_dict
print
print "this is the pickle file"
pickle.dump( two_dict, open( test_file, "wb" ) )
print open(test_file, "rb").read()
print

print "update pickle test"
pickle_list = pickle.load(open(test_file, "rb"))
print "this python object is read back:"
print pickle_list
print
d1, d2 = pickle_list
two_dict = [d1, d2]
d1['time'] = d2['time'] = datetime.datetime.now().time()
pickle.dump( two_dict, open( test_file, "wb" ) )
print "this is the updated pickle:"
print open(test_file, "rb").read()
print

print "and this is the updated python:"
print pickle.load(open(test_file, "rb"))

...以及它的输出结果

first pickle test
this python list gets pickled:
[{1: 'a'}, {2: 'b'}]

this is the pickle file
(lp0
(dp1
I1
S'a'
p2
sa(dp3
I2
S'b'
p4
sa.

update pickle test
this python object is read back:
[{1: 'a'}, {2: 'b'}]

this is the updated pickle:
(lp0
(dp1
I1
S'a'
p2
sS'time'
p3
cdatetime
time
p4
(S'\n2;\x02s\x95'
p5
tp6
Rp7
sa(dp8
I2
S'b'
p9
sg3
g7
sa.

and this is the updated python:
[{1: 'a', 'time': datetime.time(10, 50, 59, 160661)}, {2: 'b', 'time': datetime.time(10, 50, 59, 160661)}]

撰写回答