Search code examples
pythondictionarychatprepend

Add object to start of dictionary


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?


Solution

  • 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:

    >>> from collections import OrderedDict
    >>> d=OrderedDict()
    >>> for i,j in [(1,'a'),(2,'b')]:
    ...    d[i]=j
    ... 
    >>> d
    OrderedDict([(1, 'a'), (2, 'b')])
    >>> d=OrderedDict([(3,'t')]+d.items())
    >>> d
    OrderedDict([(3, 't'), (1, 'a'), (2, 'b')])
    

    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 :

    >>> from collections import deque
    >>> d=deque()
    >>> d.append((1,'a'))
    >>> d.append((4,'t'))
    >>> d
    deque([(1, 'a'), (4, 't')])
    >>> d.appendleft((8,'p'))
    >>> d
    deque([(8, 'p'), (1, 'a'), (4, 't')])