Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Dictionary in place with respect to keys

I have a dictionary in C# like

Dictionary<Person, int> 

and I want to sort that dictionary in place with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated!

like image 769
SoulReaver Avatar asked Apr 24 '10 18:04

SoulReaver


People also ask

Can we sort dictionary with keys in Python?

Python offers the built-in keys functions keys() and values() functions to sort the dictionary. It takes any iterable as an argument and returns the sorted list of keys. We can use the keys to sort the dictionary in the ascending order.

How do I sort a list of dictionaries in a key?

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 does sorted work on a dictionary?

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. They use a mapping structure to store data.


1 Answers

You can't sort a Dictionary<TKey, TValue> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)

You can use SortedList<TKey, TValue> or SortedDictionary<TKey, TValue>, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T> into the constructor) - might those be of use to you?

Pay little attention to the word "list" in the name SortedList - it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary is similarly based on binary searches, but via a tree instead of a list.

like image 112
Jon Skeet Avatar answered Sep 29 '22 13:09

Jon Skeet