insert an item into a specific location in a dict in a single statement

Viewed 4949

In python 3.6 dict is ordered so now we can rely on items having certain locations. I realize that's not entirely accurate but I can't remember the exact details. Right now the only location I've been worried about is the zeroeth location. So suppose I have the following dictionary:

dict1 = {'a':1,'b':2}

And I want to insert key {'c':3} into the zeroeth location. I can do that in three lines of code, but I bet there is a shorter way to do it:

temp_dict = {}
temp_dict.update({'c':3})
dict1 = {**temp_dict,**dict1}
3 Answers

In Python 3.6+, you could define your own dict subclass that has an insert() method (since dicts started preserving insertion order at that point). With this approach it the number of lines of code isn't very significant because it's merely "implementation detail" of the new class:

class MyDict(dict):
    def insert(self, pos, new_entry):
        items = list(self.items())  # Convert current contents into a list.
        items.insert(pos, *tuple(new_entry.items()))  # Insert new entry into that list.
        self.clear()
        self.update(type(self)(items))


if __name__ == '__main__':
    dict1 = MyDict({'a': 1,'b': 2})
    dict1.insert(0, {'c': 3})
    print(dict1)  # -> {'c': 3, 'a': 1, 'b': 2}

Instances of the subclass could be used anywhere a regular dictionary object could be.

Related