Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}
like image 868
bobsmith76 Avatar asked Jan 04 '23 17:01

bobsmith76


1 Answers

enter image description here

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:])}
like image 69
Cory Madden Avatar answered Jan 06 '23 07:01

Cory Madden