Understanding Pickling in Python

前端 未结 6 1135
你的背包
你的背包 2020-12-07 18:27

I have recently got an assignment where I need to put a dictionary (where each key refers to a list) in pickled form. The only problem is I have no idea what pickled form is

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 18:58

    http://docs.python.org/library/pickle.html#example

    import pickle
    
    data1 = {'a': [1, 2.0, 3, 4+6j],
             'b': ('string', u'Unicode string'),
             'c': None}
    
    selfref_list = [1, 2, 3]
    selfref_list.append(selfref_list)
    
    output = open('data.pkl', 'wb')
    
    # Pickle dictionary using protocol 0.
    pickle.dump(data1, output)
    
    # Pickle the list using the highest protocol available.
    pickle.dump(selfref_list, output, -1)
    
    output.close()
    

提交回复
热议问题