Suppose we have a
var dictionary= new Dictionary<int, IList<int>>();
What I want is to ouput a sorted version of it, ordered first by keys and then by values inside a list.
E.g.
1 2, 1, 6
5 2, 1
2 1, 3
Becomes
1 1, 2, 6
2 1, 3
5 1, 2
I tried doing it inside foreach
, but obviously this is a bad idea to change the thing you are iterating.
To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
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.
Try this:
// Creating test data
var dictionary = new Dictionary<int, IList<int>>
{
{ 1, new List<int> { 2, 1, 6 } },
{ 5, new List<int> { 2, 1 } },
{ 2, new List<int> { 2, 3 } }
};
// Ordering as requested
dictionary = dictionary
.OrderBy(d => d.Key)
.ToDictionary(
d => d.Key,
d => (IList<int>)d.Value.OrderBy(v => v).ToList()
);
// Displaying the results
foreach(var kv in dictionary)
{
Console.Write("\n{0}", kv.Key);
foreach (var li in kv.Value)
{
Console.Write("\t{0}", li);
}
}
A Dictionary
is unsorted. To sort a dictionary you can use the OrderedDictionary
.
To sort the lists, you can use List<T>.OrderBy()
You can use LINQ to order the contents of the dictionary like this:
var dictionary = new Dictionary<int, IList<int>>();
var orderedItems = dictionary
.OrderBy(pair => pair.Key)
.Select(new {
Key = pair.Key,
Value = pair.Value.OrderBy(i => i)});
Of course, this is rather ugly. A better option at this point is to use LINQ syntax
var orderedItems =from pair in dictionary
orderby pair.Key
let values = pair.Value.OrderBy(i => i)
select new { Key = pair.Key, Value = values };
If you need to use the resulting IEnumerable as a list or array, you can create one using ToList or ToArray. In most cases though, you can just use the IEnumerable as it is
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With