在一个pickle文件中使用两个词典

时间:2014-08-14 23:09:53

标签: python python-2.7 dictionary pickle

我想非常明确地开始这么好开始我知道的情况所以每个人都知道我的意思。当我只在一个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文件中两个dict列表的输出:

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

正如你所看到的那样存储很奇怪,我似乎无法分别正确地访问每个字典以更新它们必须是一些语法来正确地执行此操作。

1 个答案:

答案 0 :(得分:1)

试一试!做pickle.load(),你会看到一个包含两个dicts的列表。您可以通过多种方式引用它们,但这是常用的方法:

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