user15347905
user15347905

Reputation:

is there a way to add new value at beginning of dictionary

I have this python dictionary

my_dic = {
     0:{"food":"banana"},
     1:{"food":"apple"},
     2:{"food":"orange"}
}

and I want When never I added new value to my_dic I wanted it to be in the to beginning of my_dic with key 0 so my_dic looks like that

my_dic = {
     0:{new value},
     1:{"food":"banana"},
     2:{"food":"apple"},
     3:{"food":"orange"}
}

Upvotes: 0

Views: 72

Answers (1)

576i
576i

Reputation: 8352

This is how you can do it

my_dic = {
     0:{"food":"banana"},
     1:{"food":"apple"},
     2:{"food":"orange"}
   }

my_dic = {0: "New value", **{k+1: v for k, v in my_dic.items()}}

which basically creates a new dict and puts the old one at the end.

This returns

{0: 'New value', 1: {'food': 'banana'}, 2: {'food': 'apple'}, 3: {'food': 'orange'}}

Since this is not performant, you should check, if you can do with another data structure. Many commenters suggested using a collections.deque() and that's what I would chose myself as well.

Upvotes: 1

Related Questions