Hashtables and key order

powershell ordered hashtable
powershell hashtable
about hashtables
powershell hashtable preserve order
sort hash table
powershell hashtable foreach
powershell hashtable array
powershell nested hash table

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.

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

Ordered Hash Tables and Changing Order - Power Tips, Unlike regular hash tables, ordered hash tables keep the order in which you add keys, so you can control in which order these keys turn into object properties. E.g. sort by (hashed) order property and return the key (country): Or sort (descending) by the predefined capital: But the question was about keeping the order in which the hash was added to, not sorting by keys or sort by values. The PowerShell 1 way is to add a hashtable member to retain the add order.

You can use an ordered dictionary instead:

Like this:

$list = New-Object System.Collections.Specialized.OrderedDictionary
$list.Add("Switzerland", "Bern")
$list.Add("Spain", "Madrid")
$list.Add("Italy", "Rome")
$list.Add("Germany", "Berlin")
$list

Weekend Scripter: Sorting PowerShell Hash Tables, As you can see, they are not in order. All I need to do is to pipe the hash table to the Sort-Object cmdlet, Name AliasProperty Name = Key. A Hashtable provides a key-value lookup functionality. Hashtable in java.util.Hashtable is not guaranteed to Enumerate (or Iterate) keys in the same order as they were put in. This article explains how to implement ordering in a Hashtable.

You can give one sequential key as you add elements:

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

Then, you can get elements sorted by the key:

echo "`nHashtable keeping the order as they were added"
foreach($item in $hashtable.getEnumerator() | Sort Key)
{
    $item
}

about_Hash_Tables, The order of keys in a hash table is not determined. You can also create nested hash tables, in which the value of a key is another hash table. Powershell - Hashtables Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys.

Here is a simple routine that works for me.

function sortedKeys([hashtable]$ht) {
  $out = @()
  foreach($k in $ht.keys) {
    $out += $k
  }
  [Array]::sort($out)
  return ,$out
}

and the call to use it

forEach($k in (& sortedKeys $ht)) {
  ...
}

How to sort Hashtable in java, Hashtable doesn't preserve the insertion order, neither it sorts the inserted data based on keys or values. Which means no matter what keys & values you insert into Hashtable, the result would not be in any particular order. As you can see that the output key-value pairs are in random order. In other words, a hashtable is an associative array or a dictionary with a key-value pair. A key/value pair is essentially a set of two elements that are related in some manner. In a hashtable, the input is a unique key with an associated value and output is a table with two columns.

The PowerShell 1 way is to add a hashtable member to retain the add order. There is no need to use System.Collections.Specialized.OrderedDictionary:

$Hash = New-Object PSObject                                       
$Hash | Add-Member -MemberType NoteProperty -Name key1 -Value val1
$Hash | Add-Member -MemberType NoteProperty -Name key2 -Value val2
$Hash | Add-Member -MemberType NoteProperty -Name key3 -Value val3

Why can't hash tables preserve the order of keys? – Daniel Lemire's , Since the primary focus of a hashtable is to simply map keys to values, you should not depend on it to retain any ordering whatsoever—such as the order you  The idea of hashing is to distribute entries (key/value pairs) uniformly across an array. Each element is assigned a key (converted key). By using that key you can access the element in O(1) time. Using the key, the algorithm (hash function) computes an index that suggests where an entry can be found or inserted. Hashing is implemented in two

Sort a Hashtable by Key or Value in Windows PowerShell, To sort on the keys, you can use the GetEnumerator() method which is Now the hash table will always be sorted in the order you defined the  The order of keys in a hash table is not determined. The keys and value in hash tables are also .NET objects. They are most often strings or integers, but they can have any object type. You can also create nested hash tables, in which the value of a key is another hash table.

Sorting Hash Tables • The Lonely Administrator, This crate implements compact map and set data-structures, where the iteration order of the keys is independent from their hash or value. It preserves insertion  Long story short, the key, literally, is the key to working with Hash Tables.. Once you’ve mastered that, you can then start implementing advanced logic, such as detecting the object type, or well, anything other than simply outputting the value to the console.

bluss/indexmap: A hash table with consistent order and fast , Hash tables are used to implement dictionary and map data structures. A hash table is an unordered collection of key-value pairs, where each key is unique. string,; and that the value changes when we change the order of the characters. By default, hashtables are not ordered (or sorted). In the traditional context, the order does not matter when you always use a key to access values. You may find that when using it to hold properties that you may want them to stay in the order that you define them. Thankfully, there is a way to do that with the ordered keyword.

Comments
  • Thanks for the answers! I knew the PS v3 [ordered] but I must use PS 2.0
  • But the question was about keeping the order in which the hash was added to, not sorting by keys. How does this answer the question?
  • Peter, you are correct. I was confused and thought Ordered dictionary was like a Java TreeMap not a LinkedHashMap. Thanks for the clarification.
  • But that's not a hashtable, it's a PSCustomObject. Not the same thing, even if you name the variable "$Hash". ;) An OrderedDictionary functions just like a hashtable for all practical purposes that I've tried.
  • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.How to Answer. Thanks!