Learn Python in 30 Days — Day 12: Dictionaries

Learn Python in 30 Days — Day 12: Dictionaries

Welcome to Day 12 of the Learn Python in 30 Days series!

Yesterday we explored tuples and sets, which let you store ordered and unique data.
Today, we move on to something that will become a cornerstone of your Python projects dictionaries.

Dictionaries are the foundation of nearly every real-world Python application be it configuration files, APIs, game states, and even databases, they all rely on this structure.
Think of them as mini databases in memory, perfect for storing information with named labels instead of numbered positions.

By the end of this lesson you’ll be able to:

  • Create and manipulate dictionaries with confidence

  • Understand how keys and values work under the hood

  • Store nested and complex data structures

  • Combine loops and conditionals to build a Contact Book mini-project

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

What is a Dictionary?

A dictionary stores data as key → value pairs.

Instead of lists, which rely on numeric positions, dictionaries let you store data under descriptive labels:

user = { "name": "Matty", "age": 32, "is_admin": True }

Access values by their keys:

print(user["name"]) # Matty print(user["age"]) # 32

They’re also known as hash maps in other languages, and they’re fast. Python dictionaries use hash tables internally, giving you near-instant lookups even in large data sets.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Creating Dictionaries

There are a few ways to create dictionaries.

# Using curly braces person = { "name": "Alex", "job": "Engineer", "country": "UK" } # Using the dict() constructor settings = dict(theme="dark", autosave=True) # Creating an empty dictionary data = {} # Keys must be unique; duplicates overwrite demo = {"name": "Alex", "name": "Sam"} print("Person:", person) print("Settings:", settings) print("Empty:", data) print("Duplicate key example:", demo)

Explanation:

  • {} creates a dictionary

  • Each key is separated by a colon from its value

  • Commas separate items

  • Duplicate keys will overwrite previous ones

Expected Output:

Person: {'name': 'Alex', 'job': 'Engineer', 'country': 'UK'} Settings: {'theme': 'dark', 'autosave': True} Empty: {} Duplicate key example: {'name': 'Sam'}

Keys must be unique and immutable (e.g. strings, numbers, tuples). If you repeat a key, the last one wins.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Accessing and Reading Data

You can access values using their keys, not numbers like in a list.

person = {"name": "Alex", "job": "Engineer", "country": "UK"} # Access directly print(person["name"]) # Output: Alex

If the key doesn’t exist, Python will raise an error.
To avoid that, use .get():

print(person.get("email", "Not provided"))

.get() safely checks if a key exists and returns a default message if not.

Expected Output:

Alex Not provided

Why use .get()?
It prevents your program from crashing if the key is missing — very useful when working with user or file data.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Adding and Updating Entries

Dictionaries are flexible — you can add new data or update existing items anytime.

person = {"name": "Alex", "job": "Engineer"} # Add new keys and values person["age"] = 30 person["country"] = "UK" # Update multiple at once person.update({"city": "London", "verified": True}) print(person)

Explanation:

  • Adding is just assigning a new key

  • .update() adds or changes multiple keys at once

Expected Output:

{'name': 'Alex', 'job': 'Engineer', 'age': 30, 'country': 'UK', 'city': 'London', 'verified': True}

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Removing Items

You can remove items in several ways.

person = {"name": "Alex", "age": 30, "city": "London"} # Delete by key del person["city"] # Delete and return a value age = person.pop("age") print("Removed age:", age) # Safe delete (no error if key not found) person.pop("email", "No email found") # Clear everything person.clear() print("After clear:", person)

Explanation:

  • del removes a key but errors if missing

  • .pop() removes and returns a value

  • .clear() empties the dictionary

Expected Output:

Removed age: 30 After clear: {}

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Dictionary Views (Keys, Values, Items)

You can easily view all keys, values, or both at once.

person = {"name": "Alex", "job": "Engineer", "country": "UK"} print(person.keys()) # Shows all keys print(person.values()) # Shows all values print(person.items()) # Shows both

Expected Output:

dict_keys(['name', 'job', 'country']) dict_values(['Alex', 'Engineer', 'UK']) dict_items([('name', 'Alex'), ('job', 'Engineer'), ('country', 'UK')])

These are live views if you change the dictionary, these update automatically.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Looping Through Dictionaries

Dictionaries are perfect for looping through data.

person = {"name": "Alex", "job": "Engineer", "country": "UK"} # Loop over just keys for key in person: print(key, ":", person[key]) # Loop over both key and value for key, value in person.items(): print(f"{key}{value}")

Explanation:

  • Looping directly gives you the keys

  • .items() lets you unpack both key and value for cleaner loops

Expected Output:

name : Alex job : Engineer country : UK name Alex job Engineer country UK

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Checking for Keys

You can check if a key exists before using it.

person = {"name": "Alex", "job": "Engineer"} if "name" in person: print("Name exists!") else: print("Name not found.")

Explanation:
The in keyword checks for membership quickly — faster than looping through keys manually.

Expected Output:

Name exists!
Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Nested and Complex Dictionaries

Dictionaries can hold other dictionaries or lists — this is how you store structured data (like JSON files).

Dictionary inside a Dictionary

users = { "matty": { "name": "Matty", "role": "admin", "likes_python": True }, "alex": { "name": "Alex", "role": "editor", "likes_python": False } } print(users["matty"]["role"])

List inside a Dictionary

playlist = { "name": "Coding Tunes", "songs": ["Track 1", "Track 2", "Track 3"] } print("Playlist name:", playlist["name"]) print("Songs:", playlist["songs"])

Dictionaries inside a List

products = [ {"name": "Soldering Iron", "price": 25.0}, {"name": "Breadboard", "price": 5.0} ] for product in products: print(f"{product['name']} - £{product['price']}")

Expected Output:

admin Playlist name: Coding Tunes Songs: ['Track 1', 'Track 2', 'Track 3'] Soldering Iron - £25.0 Breadboard - £5.0

Why use nested dictionaries?

This is the structure used in JSON, the universal data format you’ll soon encounter when working with files and web data.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Advanced Insight — How Dictionaries Work Internally

Python dictionaries are hash tables.
When you create a key, Python:

  1. Computes a unique hash value for that key

  2. Maps it to a position in memory

  3. Stores or retrieves the value in constant time, O(1)

That’s why dictionary lookups are far faster than scanning through lists.
However, this also means:

  • Keys must be immutable

  • You cannot use lists or other dictionaries as keys

Practical Tip: Dictionary Comprehensions

You can quickly create dictionaries using a short syntax, similar to list comprehensions.

squares = {x: x**2 for x in range(5)} print(squares)

Explanation:
This loops through numbers 0–4, and for each number x, it stores x as the key and x**2 (x squared) as the value.

Expected Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Mini Project — Simple Contact Book

Let’s put all this into action with a Contact Book that uses dictionaries as an in-memory database.

contacts = {} while True: print("\n--- Contact Book ---") print("1. Add / Update Contact") print("2. View Contact") print("3. View All Contacts") print("4. Delete Contact") print("5. Quit") choice = input("Choose an option (1-5): ").strip() if choice == "1": name = input("Name: ").strip() phone = input("Phone: ").strip() email = input("Email (optional): ").strip() contacts[name] = { "phone": phone, "email": email if email else "Not provided" } print(f"Saved contact for {name}.") elif choice == "2": name = input("Enter name to look up: ").strip() contact = contacts.get(name) if contact: print(f"\n{name}") print(f"Phone: {contact['phone']}") print(f"Email: {contact['email']}") else: print("No contact found with that name.") elif choice == "3": if not contacts: print("No contacts saved yet.") else: print("\nAll contacts:") for name, info in contacts.items(): print(f"- {name}: {info['phone']} ({info['email']})") elif choice == "4": name = input("Enter name to delete: ").strip() removed = contacts.pop(name, None) if removed: print(f"Deleted contact for {name}.") else: print("No contact found with that name.") elif choice == "5": print("Goodbye!") break else: print("Invalid choice. Please try again.")

Concepts used:

  • Dictionaries as data stores

  • .get() and .pop() for safe access

  • .items() for looping

  • Lists, conditionals, and formatted output

This is your first small “application” a working, stateful tool built entirely from what you’ve learned so far.

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Wrap-Up

You now understand one of Python’s most versatile and powerful data types.

Dictionaries = Fast, structured, and human-readable data.

They’re the backbone of almost everything you’ll do from now on — from managing user profiles and app settings to reading JSON from APIs.

Next up — Day 13 – Nested Structures & Looping

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

Math Behind Logic Gates

6502 - Part 2 Reset and Clock Circuit

Building a 6502 NOP Test