0

Okay, so, I have something that looks like this:

[ 
  { "abc": "123",
    "id": 9,
  },
  { "azc": "153",
    "id": 2,
  },
  { "oau": "321",
    "id": 9,
  },
]

As you can see above, it can happen that the ID duplicates in the file I have, however, I'd like that if the ID is duplicated in two of these lists, one of the lists is deleted, and the other is kept.

Is it possible? I've been trying for way too long now.

Folfy Blue
  • 21
  • 1

1 Answers1

0

You can use dict comprehension to build a dict with the id key of each sub-dict in the list as the key and the sub-dict as the value, so that duplicating entries would be overridden by the latter values (assuming your list of dicts is stored in variable l):

list({d['id']: d for d in l}.values())

This returns:

[{'oau': '321', 'id': 9}, {'azc': '153', 'id': 2}]
blhsing
  • 91,368
  • 6
  • 71
  • 106