Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Beginner  ·  Lesson 14

Dictionaries in Python

In this lesson: Create and use Python dictionaries — keys, values, get, update, pop, items loop — with practical examples and output.

What is a Dictionary?

A dictionary stores data as key : value pairs inside curly braces { }. You look up a value using its key — like a real dictionary where the word is the key and the meaning is the value.

Python – dict.py
student = {"name": "Aman", "class": 12, "marks": 95}
print(student["name"])
print(student["marks"])
Aman 95

Access, Add, Update

Python – modify.py
student = {"name": "Aman", "marks": 95}
student["class"] = 12        # add a new key
student["marks"] = 98        # update existing
print(student)
{'name': 'Aman', 'marks': 98, 'class': 12}
  • Assigning to a new key adds it.
  • Assigning to an existing key updates it.

Dictionary Methods

MethodDoes
.keys()all keys
.values()all values
.items()all key-value pairs
.get(k)value of k (no error if missing)
.pop(k)remove key k

Program 1: Student Record

Python – record.py
student = {
    "name": "Riya",
    "roll": 12,
    "marks": [88, 92, 79]
}
print("Name :", student["name"])
print("Roll :", student["roll"])
print("Total:", sum(student["marks"]))
Name : Riya Roll : 12 Total: 259

A value can itself be a list — here marks holds three numbers we add with sum().

Program 2: Loop Through a Dictionary

Python – loopdict.py
prices = {"pen": 10, "book": 50, "bag": 400}
for item, price in prices.items():
    print(item, "costs", price)
pen costs 10 book costs 50 bag costs 400

.items() gives each key and value together, so the loop reads both at once.

Program 3: Count Word Frequency

Python – freq.py
text = "apple banana apple cherry banana apple"
words = text.split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq)
{'apple': 3, 'banana': 2, 'cherry': 1}
  • freq.get(w, 0) returns the current count or 0 if the word is new.
  • We add 1 each time the word appears — a classic counting pattern.

Program 4: Simple Phone Book

Python – phonebook.py
book = {}
book["Aman"] = "98765"
book["Riya"] = "91234"

name = input("Whose number? ")
if name in book:
    print(name, ":", book[name])
else:
    print("Not found")
Whose number? Riya Riya : 91234

Common Mistakes

  • Accessing a missing key with dict[key] causes a KeyError — use .get().
  • Keys must be unique; a repeated key overwrites the old value.
  • Lists cannot be keys (keys must be immutable).

Practice Tasks

  1. Make a dictionary of 3 students and their marks; print the topper.
  2. Count how many times each character appears in a word.
  3. Build a small English-Hindi dictionary and look up a word.
  4. Store product prices and print the total bill.

Summary

  • Dictionaries store key:value pairs in { }.
  • Access by key; assigning adds or updates.
  • Use .items() to loop, .get() to avoid KeyError.
  • Great for records, counting and lookups.

Frequently Asked Questions

How do I avoid a KeyError when reading a dictionary?
Use d.get(key) or d.get(key, default), which returns None or the default instead of raising an error.
Can dictionary keys be lists?
No. Keys must be immutable (hashable) such as str, int or tuple. Values can be any type.
How do I loop over keys and values together?
Use for key, value in d.items():
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicString Handling in Python Your progress: 14 / 66 (21%) · Lesson 15 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free