Dictionary and Hash Table

We will learn about PowerShell hash tables and Python dictionaries. This will include how they are created, accessed, adding and removing elements, and some built-in methods.

Hashtable

A PowerShell hash table, also known as a dictionary or an associative array, is a data structure that stores one or more key-value pairs. To create a hash table, we use an at (@) symbol followed by open and close braces. Inside the braces, we can define a key-value pair separated by the equals (=) operator. If there are multiple key-value pairs, we separate them by a semi-colon (;).

Syntax:

@{key1=value1; key2=value2; key3=value3 ....}

For example, a hash table might contain details like the first, middle, last name, and age of an employee.

$employee = @{first='Prateek';middle='kumar';last='singh';age=28}

Dictionary

A dictionary in Python is an unordered, changeable collection that stores indexed key-value pairs. In Python, dictionaries are written with curly brackets. Creating a dictionary is as simple as placing items inside curly braces { } separated by a comma.

A key-value pair is separated by a colon (:)

Syntax:

employee = {key1:value1, key2:value2, key3:value3 ....}

While values can be of any data type and can even repeat, each key in a dictionary must be unique. For example, let’s see how employee details can be stored in a Python dictionary:

employee = {'first':'Prateek', 'middle':'kumar', 'last':'singh', 'age':28}

Now let’s learn about operations that can be performed on a dictionary or hash table.

Get hands-on with 1400+ tech skills courses.