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}
One line:
dict1 = {k: v for k, v in ([('c', 3)] + list(dict1.items()))}
That was fun. I didn't even have 3.6 installed yet.
Because I found this task so amusing, here's a one line function to insert an item into any position in the dict:
insert = lambda _dict, obj, pos: {k: v for k, v in (list(_dict.items())[:pos] +
list(obj.items()) +
list(_dict.items())[pos:])}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With