sorting a list of lists of dictionaries in python

  • Last Update :
  • Techknowledgy :

Your idea is already very good, to use a custom key function when sorting and using sum, map and an itemgetter on the play key:

key = sum(map(itemgetter(play)))

The other problems are that play should be a string 'play' instead, and that map should take the sublist as an argument. So your key function would look like this:

key = lambda x: sum(map(itemgetter('play'), x))

This is btw. functionally equivalent to the following generator comprehension which might be more readable:

key = lambda x: sum(y['play']
   for y in x)

Suggestion : 2

Last Updated : 05 Jul, 2022

Output:

The list printed sorting by age: [{
   'age': 19,
   'name': 'Nikhil'
}, {
   'age': 20,
   'name': 'Nandini'
}, {
   'age': 20,
   'name': 'Manjeet'
}]

The list printed sorting by age and name: [{
   'age': 19,
   'name': 'Nikhil'
}, {
   'age': 20,
   'name': 'Manjeet'
}, {
   'age': 20,
   'name': 'Nandini'
}]

The list printed sorting by age in descending order: [{
   'age': 20,
   'name': 'Nandini'
}, {
   'age': 20,
   'name': 'Manjeet'
}, {
   'age': 19,
   'name': 'Nikhil'
}]

Suggestion : 3

In this article, you’ve learned how to sort a list of dictionaries. In summary, use the sorted() method with a key function as argument. This gives you the flexibility to customize how exactly you want to sort the dictionary—just map each dictionary to a comparable value.,In this article, you’ll learn the ins and outs of the sorting function in Python. In particular, you’re going to learn how to sort a list of dictionaries in all possible variations. [1] So let’s get started!,Use the itemgetter function as key function to sort the list of dictionaries.,Solution: Define a key function with the lambda keyword. Simply return the string value for the key 'joined' for a given dictionary. This return value is then used to sort the dictionaries in the list.

Minimal Example: Consider the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{
      'Alice': 100000,
      'Bob': 24000
   },
   {
      'Alice': 121000,
      'Bob': 48000
   },
   {
      'Alice': 12000,
      'Bob': 66000
   }
]

sorted_salaries = #...Sorting Magic Here...

   print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{
      'Alice': 12000,
      'Bob': 66000
   },
   {
      'Alice': 100000,
      'Bob': 24000
   },
   {
      'Alice': 121000,
      'Bob': 48000
   }
]

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Create the dictionary of Bob 's and Alice'
s salary data
salaries = [{
      'Alice': 100000,
      'Bob': 24000
   },
   {
      'Alice': 121000,
      'Bob': 48000
   },
   {
      'Alice': 12000,
      'Bob': 66000
   }
]

# Use the sorted()
function with key argument to create a new dic.
# Each dictionary list element is "reduced"
to the value stored
for key 'Alice'
sorted_salaries = sorted(salaries, key = lambda d: d['Alice'])

# Print everything to the shell
print(sorted_salaries)

Minimal Example: Consider again the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{
      'Alice': 100000,
      'Bob': 24000
   },
   {
      'Alice': 121000,
      'Bob': 48000
   },
   {
      'Alice': 12000,
      'Bob': 66000
   }
]

sorted_salaries = #...Sorting Magic Here...

   print(sorted_salaries)

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'username'. If the 'username' is the same, you use the 'joined' value as a tiebreaker. If the 'joined' date is the same, you use the 'age' as a tie breaker.

db = [{
      'username': 'Alice',
      'joined': 2020,
      'age': 23
   },
   {
      'username': 'Bob',
      'joined': 2018,
      'age': 19
   },
   {
      'username': 'Alice',
      'joined': 2020,
      'age': 31
   }
]

sorted_salaries = #...Sorting Magic Here...

   print(sorted_salaries)

Suggestion : 4

The Python sort() method sorts the elements of a list in a given order, including ascending or descending orders. The method works in place, meaning that the changed list does not need to be reassigned in order to modify the list.,In the following section, you’ll learn how to sort a list in descending order using the Python .sort() method.,In the following sections, you’ll learn how to use the .sort() method to sort values in a list. First, you’ll learn how to sort a list in ascending order.,Say we wanted to sort the list of people by their age, in ascending order. In order to do this, we need to access the value for the 'Age' key. We can do this by using the .get() method.

Let’s take a look at the parameters of the function:

# The Parameters of the.sort Method
list.sort(
   key = None,
   reverse = False)

Let’s take a look at an example of how to sort a list in ascending order in Python:

# Sorting a List in Ascending Order
name = ['d', 'a', 't', 'a', 'g', 'y']
name.sort()
print(name)

# Returns:
   #['a', 'a', 'd', 'g', 't', 'y']

Let’s see how we can sort a list in reverse order using the .sort() method:

# Sorting a List in Descending Order
name = ['d', 'a', 't', 'a', 'g', 'y']
name.sort(reverse = True)
print(name)

# Returns:
   #['y', 't', 'g', 'd', 'a', 'a']

Let’s see what this looks like:

# Sorting a List of Letters With Mixed Capitalization
name = ['D', 'a', 't', 'a', 'g', 'y']
name.sort(key = str.lower)
print(name)

# Returns:
   #['a', 'a', 'D', 'g', 't', 'y']

Let’s take a look at an example of how we can do this:

# Sorting a List with a Custom Function
words = ['apple', 'banana', 'grapefruit', 'plum']

def get_last(word):
   return word[-1]

words.sort(key = get_last)
print(words)

# Returns:
   #['banana', 'apple', 'plum', 'grapefruit']

Suggestion : 5

5.1.3. List Comprehensions,5.7. More on Conditions,5.1.2. Using Lists as Queues,5.1.1. Using Lists as Stacks

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>>
   fruits.count('apple')
2
   >>>
   fruits.count('tangerine')
0
   >>>
   fruits.index('banana')
3
   >>>
   fruits.index('banana', 4) # Find next banana starting a position 4
6
   >>>
   fruits.reverse() >>>
   fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>>
   fruits.append('grape') >>>
   fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>>
   fruits.sort() >>>
   fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>>
   fruits.pop()
'pear'
>>> stack = [3, 4, 5] >>>
   stack.append(6) >>>
   stack.append(7) >>>
   stack[3, 4, 5, 6, 7] >>>
   stack.pop()
7
   >>>
   stack[3, 4, 5, 6] >>>
   stack.pop()
6
   >>>
   stack.pop()
5
   >>>
   stack[3, 4]
>>> from collections
import deque
   >>>
   queue = deque(["Eric", "John", "Michael"]) >>>
   queue.append("Terry") # Terry arrives >>>
   queue.append("Graham") # Graham arrives >>>
   queue.popleft() # The first to arrive now leaves 'Eric' >>>
   queue.popleft() # The second to arrive now leaves 'John' >>>
   queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
>>> squares = [] >>>
   for x in range(10):
   ...squares.append(x ** 2)
   ...
   >>>
   squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = list(map(lambda x: x ** 2, range(10)))
squares = [x ** 2
   for x in range(10)
]