Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtables and key order

Is there a way to keep the order of keys in a hashtable as they were added? Like a push/pop mechanism.

Example:

$hashtable = @{}  $hashtable.Add("Switzerland", "Bern") $hashtable.Add("Spain", "Madrid") $hashtable.Add("Italy", "Rome") $hashtable.Add("Germany", "Berlin") $hashtable 

I want to retain the order in which I've added the elements to the hashtable.

like image 587
Philipp Avatar asked Feb 15 '13 08:02

Philipp


People also ask

Are Hashtables ordered?

Hashtable is a data structure that stores data in key-value format. The stored data is neither in sorted order nor preserves the insertion order.

When should you not use Hashtables?

There are some operations which are not efficiently supported by hash tables, such as iterating over all the elements whose keys are within a certain range, finding the element with the largest key or smallest key, and so on. The O(n) complexity is on average.

Does hashing maintain key order?

Question: Why can't hash tables preserve the order of keys? Answer: There is no fundamental reason why they can't. If you knew enough about your problem, you could design an order preserving hash function (i.e., f(k2)< f(k1) whenever k2< k1).

Why is Hashtable not ordered?

A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. Since the index in the array is calculated and there are various hash functions, that means that no order of keys is guaranteed.


1 Answers

There is no built-in solution in PowerShell V1 / V2. You will want to use the .NET System.Collections.Specialized.OrderedDictionary:

$order = New-Object System.Collections.Specialized.OrderedDictionary $order.Add("Switzerland", "Bern") $order.Add("Spain", "Madrid") $order.Add("Italy", "Rome") $order.Add("Germany", "Berlin")   PS> $order  Name                           Value ----                           ----- Switzerland                    Bern Spain                          Madrid Italy                          Rome Germany                        Berlin 

In PowerShell V3 you can cast to [ordered]:

PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}  Name                           Value ----                           ----- Switzerland                    Bern Spain                          Madrid Italy                          Rome Germany                        Berlin 
like image 145
Loïc MICHEL Avatar answered Sep 21 '22 15:09

Loïc MICHEL