I am making a group chatting app and I have images associated with the users, so whenever they say something, their image is displayed next to it. I wrote the server in python and the client will be an iOS app. I use a dictionary to store all of the message/image pairs. Whenever my iOS app sends a command to the server (msg:<message
), the dictionary adds the image and message to the dictionary like so:dictionary[message] = imageName
, which is converted to lists then strings to be sent off in a socket. I would like to add the incoming messages to the start of the dictionary, instead of the end. Something like
#When added to end:
dictionary = {"hello":image3.png}
#new message
dictionary = {"hello":image3.png, "i like py":image1.png}
#When added to start:
dictionary = {"hello":image3.png}
#new message
dictionary = {"i like py":image1.png, "hello":image3.png}
Is there any way to add the object to the start of the dictionary?
First of all it doesn't added the item at the end of dictionary because dictionaries use hash-table to storing their elements and are unordered. if you want to preserve the order you can use
collections.OrderedDict
.but it will appends the item at the end of your dictionary. One way is appending that item to the fist of your items then convert it to an Orderd:Also as another efficient way if it's not necessary to use a dictionary you can use a
deque
that allows you to append from both side :