0

In python3, (specifically 3.6 onwards) the dictionary keeps the ordering, which is great. However, I would like to initialize a dict with a kv pair 'at the end'. For example:

>>> data = {
    'Z': []
    # 'from': ['tos'], // adjacency list
}
>>> data['a']='b'
>>> data['b']='c'

>>> data
{'Z': [], 'a': 'b', 'b': 'c'}

Is this possible to do? What I want is as follows:

>>> data
{'a': 'b', 'b': 'c', 'Z': []} # 'Z' is the last element
S3DEV
  • 8,768
  • 3
  • 31
  • 42
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

1

I am not 100% certain if I understand what you would like to do but is it this:

from collections import OrderedDict
data = OrderedDict({
    'Z': []
})

def add_to_dict(key, value): 
    data[key] = value
    data.move_to_end('Z')

add_to_dict('a', 'b')
print(data).  # OrderedDict([('a', 'b'), ('Z', [])])
BStadlbauer
  • 1,287
  • 6
  • 18
  • Me too. Alternatives seem to be discussed in https://stackoverflow.com/questions/16664874/how-to-add-an-element-to-the-beginning-of-an-ordereddict – antont Feb 07 '20 at 23:35
0
class CustomDict(dict):
    def move_to_end(self, key):
        value = self[key]
        del self[key]
        self[key] = value


d = CustomDict({"z": [], "hey": "world"})
d.move_to_end("z")
print(d)

Outputs:

{'hey': 'world', 'z': []}

You could also create a custom dict object to automatically place the key z unto the end, but that is a bit more work. Check out this post here for reference.

felipe
  • 7,324
  • 2
  • 28
  • 37
-2

Not sure if you're referring to reversing the data within the dict once new data is added i.e a new k,v pair but this is how you can add to a current dictionary:

class storeDict(dict):

    def __init__(self):
       self = dict()

    def add(self, key, value):
       self[key] = value

    # create instance of class storeDict
    newDict = storeDict()
    newDict.add('apples', 1)
    newDict.add('oranges', 2)

this just an example, that can be applicable to your question. Hope that helps :)

de_classified
  • 1,927
  • 1
  • 15
  • 19