Python sort associative array by value

Use the sorted function's key parameter:

sorted(people, key=lambda dct: dct['name'])

There is an excellent Sorting HOWTO which explains how this works.


>>> people = [
    {'name' : 'Bob', 'number' : '123'},
    {'name' : 'Bill', 'number' : '234'},
    {'name' : 'Dave', 'number' : '567'},
]       
>>> sorted(people, key=lambda dct: dct['name'])
[{'name': 'Bill', 'number': '234'}, 
 {'name': 'Bob', 'number': '123'}, 
 {'name': 'Dave', 'number': '567'}]

Alternatively, you could use

import operator
sorted(people, key=operator.itemgetter('name'))

Using operator.itemgetter('name') is slightly faster than using lambda dct: dct['name'].

Each entry in the associative array is characterized by a unique key-value pair. An array can contain singular data types belonging to variables or other arrays as its elements. There are multiple ways to sort an array of associative arrays by the value of a specified key. 

Approach 1: Using the array_multisort() method

The array_multisort() method is used to return a sorted array. String keys will be maintained, but the numeric keys are re-indexed, and they start at 0 and increase by 1. This function can sort multiple arrays at once or a multidimensional array. 

array_multisort(array, sort_order, sort_type);

Example: In this approach, initially an array of associative arrays is defined. Then, a new array is created in order to store the keys as the attribute of the main array upon which we wish to sort. The array_multisort() method is then applied to this created array and the desired sort type. In case two or more keys are the same, the values appear in the order of storage. 

PHP

 #declaring an associative array

$arr = array(

   array("Name"=>"YASHIKA", "marks"=>22),

   array("Name"=>"ASHIKA", "marks"=>67),

   array("Name"=>"BASHIKA", "marks"=>87),

   array("Name"=>"YASHITA", "marks"=>24),

   array("Name"=>"AMAN", "marks"=>55),

   array("Name"=>"ANjali", "marks"=>98),

   array("Name"=>"YASHIKA", "marks"=>100),   

);

#declaring an array to store names

$names = array();

#iterating over the arr

foreach ($arr as $key => $val)

{

  #storing the key of the names array as the Name key of the arr

    $names[$key] = $val['Name'];

}

#apply multisort method

array_multisort($names, SORT_ASC, $arr);

print_r("Modified Array : ");

print_r($arr);  

?>

Output:

Modified Array : Array
(
    [0] => Array
        (
            [Name] => AMAN
            [marks] => 55
        )

    [1] => Array
        (
            [Name] => ANjali
            [marks] => 98
        )

    [2] => Array
        (
            [Name] => ASHIKA
            [marks] => 67
        )

    [3] => Array
        (
            [Name] => BASHIKA
            [marks] => 87
        )

    [4] => Array
        (
            [Name] => YASHIKA
            [marks] => 22
        )

    [5] => Array
        (
            [Name] => YASHIKA
            [marks] => 100
        )

    [6] => Array
        (
            [Name] => YASHITA
            [marks] => 24
        )
)

Explanation: The main array is sorted based on names in ascending order. 

Approach 2: Using the usort() method

This method sorts the given array using a user-defined comparison function. The user-defined function should return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument. This method assigns new keys to the elements in the array. It just removes any existing keys that may have been assigned, rather than just simply reordering the keys.

usort(array, user_def_func)

Example:

PHP

#sort in descending order

function DescSort($val1,$val2)

{

  #check if both the values are equal

    if ($val1['marks'] == $val2['marks']) return 0;

  #check if not equal, then compare values

    return ($val1['marks'] < $val2['marks']) ? 1 : -1;

}

#declaring an associative array

$arr = array(

   array("Name"=>"YASHIKA", "marks"=>22),

   array("Name"=>"ASHIKA", "marks"=>67),

   array("Name"=>"BASHIKA", "marks"=>87),

   array("Name"=>"YASHITA", "marks"=>24),

   array("Name"=>"AMAN", "marks"=>55),

   array("Name"=>"ANjali", "marks"=>98),

   array("Name"=>"YASHIKA", "marks"=>100),   

);

#apply usort method on the array

usort($arr,'DescSort');

print_r("Modified Array : ");

print_r($arr);

?>

Output: The DescSort() method sorts the marks in descending order. 

Modified Array : Array
(
    [0] => Array
        (
            [Name] => YASHIKA
            [marks] => 100
        )

    [1] => Array
        (
            [Name] => ANjali
            [marks] => 98
        )

    [2] => Array
        (
            [Name] => BASHIKA
            [marks] => 87
        )

    [3] => Array
        (
            [Name] => ASHIKA
            [marks] => 67
        )

    [4] => Array
        (
            [Name] => AMAN
            [marks] => 55
        )

    [5] => Array
        (
            [Name] => YASHITA
            [marks] => 24
        )

    [6] => Array
        (
            [Name] => YASHIKA
            [marks] => 22
        )
)