Sending a Dictionary using Sockets in Python?

前端 未结 6 616
悲哀的现实
悲哀的现实 2021-01-12 06:27

My problem: Ok, I made a little chat program thing where I am basically using sockets in order to send messages over a network.

It works great, but when I decided t

6条回答
  •  天命终不由人
    2021-01-12 07:03

    If you want to use pickle you can use the loads and dumps functions.

    import pickle
    a_dict = { x:str(x) for x in range(5) }
    serialized_dict = pickle.dumps(a_dict)
    # Send it through the socket and on the receiving end:
    a_dict = pickle.loads(the_received_string)
    

    You can also use JSON in a similar fashion. I like JSON because it is human readable and isn't python specific.

    import json
    a_dict = { x:str(x) for x in range(5) }
    serialized_dict = json.dumps(a_dict)
    # Send it through the socket and on the receiving end:
    a_dict = json.loads(the_received_string)
    

提交回复
热议问题