HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Dictionaries

Dictionaries

Storing key-value pairs, accessing a value, adding/updating, safe access, and iterating with a loop.

Simple enough for a 5-year-old to understand

Dictionary: labeled boxes

While a list accesses elements by number, a dictionary accesses them by KEY. It's ideal for holding the attributes of a real person.

Your first dictionary
1
person = {"name": "Alex", "age": 36}
Curly braces; "key": value pairs.
DataCurly braces; "key": value pairs.
2
print(person["name"])
Value of the "name" key: Alex
Output / InputValue of the "name" key: Alex
3
print(person["age"])
The value of the "yas" key: 36
Output / InputThe value of the "yas" key: 36
DataOutput / Input
💡 Hint: A dictionary has no order/number; you always access a value by its key name.

Adding and updating

Example code
1
person = {"name": "Alex"}
With a single key.
DataWith a single key.
2
person["city"] = "London"
Adds a new key.
CodeAdds a new key.
3
person["name"] = "Alex L."
Updates an existing key.
CodeUpdates an existing key.
4
print(person)
{'name': 'Alex L.', 'city': 'London'}
Output / Input{'name': 'Alex L.', 'city': 'London'}
DataCodeOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.How to access the "name" value in the person = {"name": "Alex"} dictionary?

About this topic

A dictionary is a structure where you store data not by sequence number, but by KEY. In a list, you retrieve the third element by index; in a dictionary, you retrieve it with a meaningful name like "price" or "email". Real-world records — a user, a product, a configuration file — naturally take the form of dictionaries.

The biggest practical advantage of a dictionary is its speed. Searching for an element in a list requires scanning from start to finish; dictionary access by key is instant, almost regardless of the dictionary's size. That's why using a dictionary or set makes a critical difference when searching large datasets.

What you will learn

  • Creating a dictionary and reading values by key
  • Adding a new key and updating an existing one
  • Safely reading a non-existent key with get
  • Iterating using keys, values, and items
  • Checking for key existence with in
  • Storing structured data with nested dictionaries

When to use?

JSON data returned from a web service converts into a dictionary in Python; configuration files, user records, and counting operations are also handled with dictionaries.

Counting how many times values repeat in a list, quickly accessing a record by ID, or matching two datasets are classic use cases for dictionaries.

Common mistakes

Wrong

user = {"name": "Ada"}
print(user["email"])

Reading a non-existent key with square brackets raises a "KeyError: 'email'" error and stops the program. If you are not sure whether the key exists, you need to use get.

Correct

user = {"name": "Ada"}
print(user.get("email", "none"))

Wrong

counts = {}
counts["a"] += 1

Trying to increment a non-existent key gives a KeyError because there is no initial value to increment. When keeping a count, you must handle the case when the key arrives for the first time.

Correct

counts = {}
counts["a"] = counts.get("a", 0) + 1

Wrong

settings = {["a", "b"]: 1}

A dictionary key must be an immutable type; it cannot be a list. You will get a "TypeError: unhashable type: 'list'" error. You can use strings, numbers, or tuples as keys.

Correct

settings = {("a", "b"): 1}

Frequently asked questions

Is the order preserved in a dictionary?

Yes in Python 3.7 and later: dictionaries preserve insertion order, and this is now a language guarantee. In older versions, the order was undefined; you might see different information in older tutorials for this reason.

Should I use a list or a dictionary?

Look at whether you access data by sequence number or by a meaningful name. Use a list for an ordered sequence of values, and a dictionary for records where each value has a label. If you are searching through a large number of records, a dictionary is much faster.

How do I safely access a deep value in a nested dictionary?

You can use chained get: if you return an empty dictionary by default at each step, you won't get a KeyError even if one of the intermediate layers is missing. For very deep structures, it is healthier to convert the data into a class or data model.

Summary

A dictionary is a data structure that works with key-value pairs and is very fast at key-based access; it is the natural choice for JSON data and configuration. The most common mistake is reading a non-existent key with square brackets; get eliminates this risk.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code