0

I have a list of lists containing dictionaries:

[[{'event_id': 1, 'order_id': 1, 'item_id': 1, 'count': 1, 'return_count': 0, 'status': 'OK'}, 
  {'event_id': 2, 'order_id': 1, 'item_id': 1, 'count': 1, 'return_count': 0, 'status': 'OK'}],
 [{'order_id': 2, 'item_id': 1, 'event_id': 1, 'count': 3, 'return_count': 1, 'status': 'OK'}, 
  {'order_id': 2, 'event_id': 2, 'item_id': 1, 'count': 3, 'return_count': 1, 'status': 'OK'},
  {'order_id': 2, 'event_id': 1, 'item_id': 2, 'count': 4, 'return_count': 2, 'status': 'OK'}]]

For each item in the given order I only need those dictionaries whose event_id is max. So I wrote the following code:

for el in lst:
    for element in el:
        if element['event_id'] != max(x['event_id'] for x in el if element['item_id'] == x['item_id']):
            el.remove(element)

lst is the initial list. For some reason, after running the code lst remains unchanged.

martineau
  • 119,623
  • 25
  • 170
  • 301
Mansur
  • 3
  • 2

3 Answers3

1

This isn't in one line, but it does return dictionaries with the max event id

dictlist = [
    [{'event_id': 1, 'order_id': 1, 'item_id': 1, 'count': 1, 'return_count': 0, 'status': 'OK'}, 
     {'event_id': 2, 'order_id': 1, 'item_id': 1, 'count': 1, 'return_count': 0, 'status': 'OK'}],
    [{'order_id': 2, 'item_id': 1, 'event_id': 1, 'count': 3, 'return_count': 1, 'status': 'OK'}, 
     {'order_id': 2, 'event_id': 2, 'item_id': 1, 'count': 3, 'return_count': 1, 'status': 'OK'},
     {'order_id': 2, 'event_id': 1, 'item_id': 2, 'count': 4, 'return_count': 2, 'status': 'OK'}]]

max = 0
parsed = []
for item in dictlist:
    for i in item:
        if i['event_id'] > max:
            max = i['event_id']
for item in dictlist:
    for dic in item:
        if dic['event_id'] == max:
            parsed.append(dic)
Austin
  • 159
  • 2
  • 9
0

sort on "event_id" and keep only the max (last element):

result = [sorted(l, key=lambda x: x["event_id"])[-1] for l in lst]

If you want to keep all dictionaries with the max "event_id":

lsts = [[x for x in l if x["event_id"]==max(l, key=lambda x: x["event_id"])["event_id"]] for l in lst]
result = [item for sublist in lsts for item in lsts]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
0

You're trying to remove an element from a list you're iterating over, that won't work. And it's really hard to understand what you're trying to do; my suggestion would be to do something like this:

newlst = []
for el in lst:
    max_event_id = max(element['event_id'] for element in el)
    max_event_element = next(element for element in el if element['event_id'] == max_event_id)
    newlst.append(max_event_element)

The expected result ends up in the newlst variable.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • I understood my mistake. Thank you. The problem is I also need to take into account item_id. If the item_id is different for two dictionaries then these dictionaries must not be comapred – Mansur Sep 02 '21 at 20:33