Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array which contains Dictionaries?

People also ask

How do you sort an array in a dictionary?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

How do you sort an array in a dictionary python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.

How do you sort an array of elements?

rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.

How do I sort multiple dictionaries in Python?

Use a lambda function as key function to sort the list of dictionaries. Use the itemgetter function as key function to sort the list of dictionaries.


If every element in the array is a dictionary containing a certain key, you can sort the array using a sort descriptor. For instance, if every element is a dictionary containing a key called "name":

NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name"
    ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];

The other way to achieve this would be using sortedArrayUsingComparator: method

NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 valueForKey:@"value"] compare:[obj2 valueForKey:@"value"]];
}];

why don't you use a sorted dictionary where the property of sorted elements comes already with the data structure?

Please do check it out here

Hope this helps.