khashashin
khashashin

Reputation: 1137

Determine if a list of dictionaries has equivalent value

How to find out that the following list of dictionaries has equivalent score number?

sorted_list = [
   {
      "team":"team",
      "score":2,
      "matches":3,
      "goal_difference":2
   },
   {
      "team":"team",
      "score":2,
      "matches":3,
      "goal_difference":3
   },
   {
      "team":"team",
      "score":1,
      "matches":3,
      "goal_difference":-1
   },
   {
      "team":"team",
      "score":4,
      "matches":3,
      "goal_difference":3
   }
]

For example in the above list sorted_list[0].score == sorted_list[1].score. I will sort this list differently depending on the values. score has the highest priority, then goal_differences and then matches

if list has equivalent score numbers:
    sorted_list = sorted(sorted_list , key=lambda k: k['goal_differences'])
else if list has equivalent goal_differences:
    sorted_list = sorted(sorted_list , key=lambda k: k['matches'])
else sorted_list = sorted(sorted_list , key=lambda k: k['score'])

Upvotes: 1

Views: 49

Answers (2)

Recoba20
Recoba20

Reputation: 324

How to find out that the following list of dictionaries has equivalent score number?

len(set([x["score"] for x in sorted_list])) == 1

Upvotes: 0

user2390182
user2390182

Reputation: 73498

You can use an appropriate key function:

from operator import itemgetter

sorted(sorted_list, key=itemgetter('score', 'goal_difference', 'matches'))

If you want some special logic like higher score first, lower matches first, build your own key:

sorted(sorted_list, key=lambda d: (-d['score'], -d['goal_difference'], d['matches']))

Upvotes: 2

Related Questions