Asked  6 Months ago    Answers:  5   Viewed   73 times

I often have to sort a dictionary, consisting of keys & values, by value. For example, I have a hash of words and respective frequencies, that I want to order by frequency.

There is a SortedList which is good for a single value (say frequency), that I want to map it back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?




using System.Linq.Enumerable;
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
        return pair1.Value.CompareTo(pair2.Value);

Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
Tuesday, June 1, 2021
answered 6 Months ago

Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}


>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

In Python3 since unpacking is not allowed we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)
Tuesday, June 1, 2021
answered 6 Months ago

System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.

Tuesday, June 1, 2021
answered 6 Months ago

It may not be straight forward in JavaScript.

var dict = {
  "x": 1,
  "y": 6,
  "z": 9,
  "a": 5,
  "b": 7,
  "c": 11,
  "d": 17,
  "t": 3

// Create items array
var items = Object.keys(dict).map(function(key) {
  return [key, dict[key]];

// Sort the array based on the second element
items.sort(function(first, second) {
  return second[1] - first[1];

// Create a new array with only the first 5 items
console.log(items.slice(0, 5));

The first step, creating items array, is similar to Python's

items = map(lambda x: [x, var[x]], var.keys())

which can be conveniently written as

items = list(dict.items())

and the sorting step is similar to Python's sorting with cmp parameter

items.sort(cmp=lambda x, y: y[1] - x[1])

and the last step is similar to the Python's slicing operation.

print items[:5]
// [['d', 17], ['c', 11], ['z', 9], ['b', 7], ['y', 6]]
Saturday, July 3, 2021
answered 5 Months ago

Read carefully about ConcurrentDictionary. It has some unobvious features.

Here are some of them:

  • If two threads call AddOrUpdate there's no guarantees about which of factory delegates will be called and even no guarantee that if a factory delegate will produce some item that this item will be stored in dictionary.
  • Enumerator obtained by GetEnumerator call is not a snapshot and may be modified during enumeration (that doesn't cause any exceptions).
  • Keys and Values properties are snapshots of corresponding collections and may not correspond to actual dictionary state.
  • etc.

So please read about ConcurrentDictionary again and decide if this behavior is what you need.

Hope this helps!

Thursday, September 16, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :