Add object to start of dictionary

Minebomber picture Minebomber · Jun 21, 2015 · Viewed 10k times · Source

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?

Answer

Craig Anderson picture Craig Anderson · Aug 19, 2020

For the use case described it sounds like a list of tuples would be a better data structure.

However, it has been possible to order a dictionary since Python 3.7. Dictionaries are now ordered by insertion order.

To add an element anywhere other than the end of a dictionary, you need to re-create the dictionary and insert the elements in order. This is pretty simple if you want to add an entry to the start of the dictionary.

# Existing data structure
old_dictionary = {"hello": "image3.png"}

# Create a new dictionary with "I like py" at the start, then
# everything from the old data structure.
new_dictionary = {"i like py": "image1.png"}
new_dictionary.update(old_dictionary)

# new_dictionary is now:
# {'i like py': 'image1.png', 'hello': 'image3.png'}