你如何遍历多个 pickled 字典

how do you iterate over a multiple pickled dictionaries

如何 pickle 字典,然后将该字典和其他 pickled 字典写入文件。然后打开该文件并遍历 pickled 字典。

import pickle
with open('board.json', 'wb') as f:
    pickle.dump({'x':'1', 'func': str}, f)
    pickle.dump({'x':'2', 'func': open}, f)

with open('board.json', 'rb') as f:
    for p in pickle.load(f):
        print(p)

输出:

x

func

预期输出:

{'x':'1', 'func': str}

{'x':'2', 'func': open}

你最好的选择就像@Suraaj 所说的那样创建一个包含这些字典的元组。

import pickle
with open('board.json', 'wb') as f:
    pickle.dump(({'x':'1', 'func': str},{'x':'2', 'func': open}), f)

当您遍历文件时采用这种方式

with open('board.json', 'rb') as f:
    for p in pickle.load(f):
        print(p)

你得到

{'x': '1', 'func': <class 'str'>}
{'x': '2', 'func': <built-in function open>}
import pickle

with open('board.json', 'wb') as f:
    pickle.dump({'x':'1', 'func': str}, f)
    pickle.dump({'x':'2', 'func': open}, f)

with open('board.json', 'rb') as f:
    while True:
        try:
            print(pickle.load(f))
        except EOFError:
            break