prepend to a list

2.3k views Asked by At

I have two lists (of dictionaries):

[{'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'},
 {'code': '12345', 'reward': 'some reward', 'source': 'some source'}
]

and

[ {'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'}
  {'code': '12345', 'reward': 'some reward', 'source': 'some source'},
  {'code': '54321', 'reward': 'another reward', 'source': 'another source'}
]

For future purposes I want the last object in the second list to be the 'new' object

I want to create a third (or new) list with the latest entry (last one of list 2) on top to be

[ {'code': '54321', 'reward': 'another reward', 'source': 'another source'},
  {'code': '123456', 'reward': 'awesome reward', 'source': 'awesome source'}
  {'code': '12345', 'reward': 'some reward', 'source': 'some source'}
]

I am able to merge two dictionaries using Surya's suggestion here: Combine two dictionaries and remove duplicates in python

but this appends my new value. I am looking for some sort of prepend function.

Apologies if I am not clear.

Thanks in advance!

3

There are 3 answers

0
Amber On

Your ordering is with lists. You can prepend to a list by assigning to the [0:0] slice:

a = [1, 2, 3]
a[0:0] = [4]
# a is now [4, 1, 2, 3]
0
jmd_dk On

Note that lists are very efficient at appending and very inefficient at prepending. You can however prepend like this:

list.insert(0, element_to_insert)
0
petruz On

You could simply concatenate the elements of the lists:

[x for x in d2 if x not in d1] + [x for x in d2 if x in d1]