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.
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.
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.
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).
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.
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
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