-2

I have list of dict in python like this

list_qty = [{'id':1,'qty': '10'},{'id':1,'qty': '15'},{'id':2,'qty': '7'},{'id':2,'qty': '20'},{'id':2,'qty': '30'}]

i want to get last index of dict from list_qty that have same id

output that i want is:

list_qty2 = [{'id':1,'qty': '15'},{'id':2,'qty': '30'}]

anyone can help me with this?

Girish Hegde
  • 1,420
  • 6
  • 16
  • Check here https://stackoverflow.com/questions/11092511/python-list-of-unique-dictionaries – Aayush Mall Aug 20 '20 at 04:19
  • 3
    Have you tried anything at all? Like, iterate over the list backwards, keeping track of the IDs you've already seen (in a set for time efficiency) then add dicts with ID's you haven't seen to a resulting list? – juanpa.arrivillaga Aug 20 '20 at 04:20

1 Answers1

1

Dict in Python updates the value of the same key. So you can try something like this:

Python 3.x

list_qty = [{'id':1,'qty': '10'},{'id':1,'qty': '15'}, {'id':2,'qty': '7'},{'id':2,'qty': '20'},{'id':2,'qty': '30'}]
list_qty2=list({v['id']:v for v in list_qty}.values())
print(list_qty2)

[{'id': 1, 'qty': '15'}, {'id': 2, 'qty': '30'}]

Python 2.7

list_qty = [{'id':1,'qty': '10'},{'id':1,'qty': '15'}, {'id':2,'qty': '7'},{'id':2,'qty': '20'},{'id':2,'qty': '30'}]
list_qty2={v['id']:v for v in list_qty}.values()
print list_qty2

[{'id': 1, 'qty': '15'}, {'id': 2, 'qty': '30'}]
CK__
  • 1,252
  • 1
  • 11
  • 25