Dictionary

Simon Pham
4 min readMar 25, 2024

--

In previous blog posts, we talked about Lists — a fundamental programming concept in C#. In today’s blog post, let’s delve into Dictionaries.

What is a dictionary?

Similar to a list, a dictionary is also a type of collection that can store multiple elements; however, they organize and access their elements differently.

How does a dictionary store and access its elements?

While a list stores its elements with indexes, a dictionary stores its elements as key-value pairs. Each key must be unique and is used to access the corresponding value. This structure makes dictionaries ideal for fast lookups where you know the key and want to retrieve the associated value quickly.

How do I declare a dictionary?

First, let’s create a script for items in a video game.

[System.Serializable] 
public class Item
{
public string name;
public int id;
}

This script defines a simple custom class with two properties: name and ID.

Next, I’ll create another script to store the game items that I’m gonna create.

using System.Collections.Generic;
using UnityEngine;

public class ItemDB : MonoBehaviour
{
public Dictionary<int, Item> itemDictionary = new Dictionary<int, Item>();
}

Similar to lists, you need to include the “System.Collections.Generic” namespace to able to use dictionaries. Instead of declaring the variable type, we declare a key-value pair, including a key of integer type and a value of Item type.

And here’s how you can create new items and add them to the dictionary:

private void Start()
{
Item sword = new Item();
sword.name = "Sword";
sword.id = 0;

Item bread = new Item();
bread.name = "Bread";
bread.id = 1;

Item cape = new Item();
cape.name = "Cape";
cape.id = 2;

itemDictionary.Add(0, sword);
itemDictionary.Add(1, bread);
itemDictionary.Add(2, cape);
}

In the provided example, I created three items, each with a name and an ID. Then, I added each of them to the newly created dictionary. Each added item was assigned a key starting from 0.

Notes: the keys used in a dictionary do not necessarily have to be directly related to any specific property of the value.

How do I access elements in a dictionary?

Similar to a list, we can access elements in a dictionary using bracket notation, but we use the keys instead of the index.

private void Start(){
Debug.Log(itemDictionary[0].id);
Debug.Log(itemDictionary[0].name);
}

You can also loop through a dictionary and print out all the values:

foreach(KeyValuePair<int, Item> item in itemDictionary)
{
Debug.Log("Key: " + item.Key);
Debug.Log("Value: " + item.Value.name);
}

In the above code, I looped through itemDictionary and printed out each element’s key and name.

Additionally, you can choose to only print out the keys or names:

foreach(int key in itemDictionary.Keys)
{
Debug.Log("Key: " + key);
}
foreach(Item item in itemDictionary.Values)
{
Debug.Log("Item Name: " + item.name);
}

When using dictionaries, not only do keys need to be unique, but they also must exist; otherwise, you’d attempt to access an object that doesn’t exist. That’s why you should always check before accessing an object through a key.

void Start(){
if (itemDictionary.ContainsKey(10))
{
Debug.Log("You found the key");
var randowmItem = itemDictionary[10];
} else
{
Debug.Log("Key does not exist");
}
}

In the above example, I checked if the dictionary contains an item with the key of 10. Since we don’t have any item with the key of 10, we received the error message.

When to use dictionaries vs lists?

Dictionaries are great when you’re working with large collections. For example, if you’re creating a shop for your game, and when the player purchases an item, each item would need to have an ID so you’d know which item to give to the player. If your shop has hundreds of items, iterating through a list to compare the ID of each item with the ID of the item the player is purchasing would be inefficient. Using a dictionary, you can simply retrieve the correct item using the key.

--

--

No responses yet