POWERSHELL / CHAPTER 02

Hashtables, keys, and deterministic order

Intermediate

Separate key membership from the truthiness of its value.

By the end of this chapter

  • Test whether a key exists
  • Choose ordered dictionaries for stable traversal
  • Distinguish string key comparison from stored values

The idea

A hashtable maps keys to values. Testing a retrieved value in an if statement does not tell you whether the key exists: an existing key can intentionally contain zero, false, an empty string, or null. Use ContainsKey on a normal hashtable when membership is the question. Hashtable literals use case-insensitive string keys, which is convenient for many command parameters but may be wrong for case-sensitive external identifiers.

Ordinary hashtable enumeration does not promise insertion order. Use an ordered dictionary when the order itself belongs to the contract, or explicitly sort keys for a report. Also distinguish a dictionary’s data keys from its object properties; names such as Count can collide. Bracket indexing clearly expresses a data lookup, and the psbase view can access underlying object members when a collision matters.

PowerShell example
$settings = @{ Retries = 0; Enabled = $false }
$settings.ContainsKey('Retries')
[bool]$settings['Retries']
$order = [ordered]@{ First = 1; Second = 2 }
$order.Keys -join ','
Result
True
False
First,Second

Retries exists even though zero converts to false. The ordered dictionary preserves the declared key order.

Try it yourself

Build a configuration lookup that applies a default only when a key is absent.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which expression distinguishes a missing key from an existing key whose value is zero?