{}const=>[]async()letfn</>var
DevelopmentBasics

Dictionaries and Hash Tables: A Complete Guide for Beginner Developers

Learn how dictionaries and hash tables work — the most important data structures in programming. The article explains in simple language the principles of working with key-value pairs, the hashing mechanism, methods for resolving collisions, and practical examples of use.

К

Kodik

Author

5 min read

What is a dictionary?

A dictionary (map, associative array) is a data structure that stores key-value pairs. Each unique key corresponds to a certain value. It is similar to a regular dictionary, where a word (key) is associated with its definition (value).

In Python, dictionaries look like this:

student = {
    "name": "Anna",
    "age": 22,
    "specialty": "Programming"
}

print(student["name"])  # To be brought out by: Anna

JavaScript uses a similar syntax:

const student = {
    name: "Anna",
    age: 22,
    specialty: "Programming"
};

console.log(student.name);  // To be brought out by: Anna

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

Basic operations with dictionaries

Adding and changing elements

# Python
grades = {}
grades["Mathematics"] = 5
grades["Physics"] = 4
grades["Mathematics"] = 5  # Change existing value

print(grades)  # {'mathematics': 5, 'physics': 4}4}

Getting values

# Direct access (will cause an error if the key is not available)
print(grades["Mathematics"])  # 5

# Safe receipt with default value
print(grades.get("Chemistry", 0))  # 0 (no key, default value will be returned)

Deleting items

del grades["Physics"]  # Removes a key-value pair

# Or using pop (returns the deleted value)
math_grade = grades.pop("Mathematics")

Checking for the key

if "Physics" in grades:
    print("Physics grade is")
else:
    print("No rating")

What is a hash table?

A hash table is a way to implement a dictionary "under the hood". This is the magic that allows dictionaries to work very quickly.

How does a hash table work?

When you add an element to the dictionary, the following happens:

  1. Key hashing: the key is converted into a number (hash code) using a special function

  2. Position determination: based on the hash code, the index in the array is calculated

  3. Saving the value: key-value pair is stored by this index

# Simplified example of a hash function
def simple_hash(key, table_size):
    return sum(ord(char) for char in key) % table_size

# For the "cat" key and table size 10
hash_value = simple_hash("cat", 10)  # Returns a number from 0 to 9

Collisions

Sometimes different keys can give the same hash. This is called a collision. There are several ways to resolve them:

Chain method: if two pairs have the same hash, they are stored as a list with one index.

Open addressing: if the cell is occupied, the next free cell is searched.

Complexity of operations

One of the main advantages of dictionaries is their speed:

  • Adding an element: O(1) on average

  • Element search: O(1) on average

  • Deleting an element: O(1) on average

This means that the execution time of the operation does not depend on the number of elements in the dictionary. For comparison, searching in a list requires O(n) time — you need to check each element.

Practical examples of use

Counting the frequency of elements

text = "hello world"
letter_count = {}

for letter in text:
    if letter in letter_count:
        letter_count[letter] += 1
    else:
        letter_count[letter] = 1

print(letter_count)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

A more elegant way using get():

text = "hello world"
letter_count = {}

for letter in text:
    letter_count[letter] = letter_count.get(letter, 0) + 1

Data grouping

students = [
    {"name": "Anna", "group": "A"},
    {"name": "Ivan", "group": "B"},
    {"name": "Maria", "group": "A"},
]

groups = {}
for student in students:
    group_name = student["group"]
    if group_name not in groups:
        groups[group_name] = []
    groups[group_name].append(student["name"])

print(groups)
# {'A': ['Anna', 'Maria'], 'B': ['Ivan']}

Caching results

def fibonacci(n, cache={}):
    if n in cache:
        return cache[n]
    
    if n <= 1:
        return n
    
    result = fibonacci(n-1, cache) + fibonacci(n-2, cache)
    cache[n] = result
    return result

print(fibonacci(100))  # Calculated very quickly thanks to caching

When to use dictionaries?

Dictionaries are ideal for:

  • Storage of settings and configurations

  • Counting the frequency of elements

  • Quick search by unique identifier

  • Data grouping and aggregation

  • Caching calculations

  • Representations of graphs (adjacency list)

Important features

Keys must be unchangeable: in Python, keys can be strings, numbers, tuples, but not lists or other dictionaries.

# Correct
valid_dict = {
    "name": "value",
    42: "value",
    (1, 2): "value"
}

# Error! Lists are modifiable# invalid_dict = {[1, 2]: "value"}

Order of elements: in Python 3.7+ dictionaries keep the order of adding elements, but it is worth relying on this only if the order is really important.

Performance: Dictionaries consume more memory than lists, but they compensate for this with access speed.

Conclusion

Dictionaries and hash tables are fundamental data structures that every developer should understand. They allow you to effectively organize data and solve many practical problems. Understanding the principles of their work will help you write faster and more efficient code.

Start using dictionaries in your projects, and you will quickly appreciate their power and convenience. Practice on simple tasks, gradually complicating them, and soon working with dictionaries will become natural for you.

Theory is great, but real understanding comes through practice. In the application Code Hundreds of programming tasks of varying complexity await you, including exercises for working with dictionaries, hash tables, and other data structures. Solve problems at a comfortable pace and track your progress!

And we also have a lively community in Telegram! Here experienced developers help beginners, share useful materials, discuss interesting tasks and just chat about programming topics. The atmosphere is friendly and supportive — every question is important, and no one will be left unanswered. Join us! 👋

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card