How to remove duplicate dic from array and order dic by some key?

Question:

My list like below:

[
  {code:"code1",name:"name1",position:"p1"},
  {code:"code2",name:"name2",position:"p2"},
  ......
]

But there is some duplicate code in the list. My question is how to remove the duplicate code from list. I can do it by build for loop and traversal the list again and again, but I think probably there is some straightforward methods can do this in python.
I also need sorted the array by key code, how can I do it without write loop by myself?
Thanks!

Asked By: user2155362

||

Answers:

You have a list of dictionaries with keys as a variable that are not defined. It throws an error:

NameError: name ‘code’ is not defined

If I change them to the type string by enclosing the keys in quotes, I get the following:

[
    {"code": "code1", "name": "name1", "position": "p1"},
    {"code": "code2", "name": "name2", "position": "p2"}.
    ......
]

Let the above list be some_list. To remove duplicates from the list of dictionaries:

some_list = [dict(t) for t in {tuple(d.items()) for d in some_list}]

To sort the list of dicts by the key code:

some_list = sorted(some_list, key=lambda k: k['code'])
Answered By: Geeky Quentin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.