Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Unit 2 – Python Programming  ·  Lesson 09

Dictionaries in Python

What is a dictionary?

A dictionary stores data as key : value pairs in curly brackets. Each key must be unique and immutable; values can be anything. Where a list answers "what is at position 2?", a dictionary answers "what is the price of a pen?".

keyvalue
'title''Wings of Fire'
'author''A. P. J. Abdul Kalam'
'price'299
A book record stored as a dictionary

Creating and accessing

Python
book = {'title': 'Wings of Fire', 'author': 'A. P. J. Abdul Kalam', 'price': 299}
print(book['title'])
print(book.get('price'), book.get('pages'), book.get('pages', 'unknown'))
print(len(book), 'author' in book)
Wings of Fire 299 None unknown 3 True

Using d[key] for a missing key raises KeyError; get() is the safe way.

Adding, modifying, deleting

Python
stock = {'pen': 120, 'pencil': 80}
stock['eraser'] = 45        # add
stock['pen'] = 100          # modify
print(stock)
del stock['pencil']         # delete
print(stock)
print(stock.pop('eraser'), stock)
{'pen': 100, 'pencil': 80, 'eraser': 45} {'pen': 100, 'eraser': 45} 45 {'pen': 100}

Traversing

Python
population = {'Delhi': 33, 'Mumbai': 22, 'Kolkata': 15, 'Chennai': 12}   # lakh, approx.
for city in population:
    print(city, end=', ')
print()
for city, p in population.items():
    print(f'{city:<8}{"●" * (p // 3)} {p}')
Delhi, Mumbai, Kolkata, Chennai, Delhi ●●●●●●●●●●● 33 Mumbai ●●●●●●● 22 Kolkata ●●●●● 15 Chennai ●●●● 12
The same dictionary as a bar chart010203040DelhiMumbaiKolkataChennai33221512
Keys become labels, values become bar heights

Dictionary methods

Python
marks = {'Maths': 88, 'Physics': 76, 'IP': 95}
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
marks.update({'English': 81, 'Maths': 90})
print(marks)
print(sorted(marks), max(marks.values()))
print(marks.popitem(), marks)
['Maths', 'Physics', 'IP'] [88, 76, 95] [('Maths', 88), ('Physics', 76), ('IP', 95)] {'Maths': 90, 'Physics': 76, 'IP': 95, 'English': 81} ['English', 'IP', 'Maths', 'Physics'] 95 ('English', 81) {'Maths': 90, 'Physics': 76, 'IP': 95}
MethodPurpose
keys(), values(), items()All keys / values / pairs
get(k, default)Safe access
update(other)Merge another dictionary (overwrites same keys)
pop(k), popitem()Remove a key / the last pair
copy(), clear()Copy / empty
len(), sorted(), max(), min(), sum(d.values())Built-in helpers

Programs

1. Counting votes

Python
votes = ['A', 'B', 'A', 'C', 'A', 'B', 'A']
result = {}
for v in votes:
    result[v] = result.get(v, 0) + 1
print(result)
winner = max(result, key=result.get)
print('Winner:', winner, 'with', result[winner], 'votes')
{'A': 4, 'B': 2, 'C': 1} Winner: A with 4 votes

2. Employee salary dictionary

Python
n = int(input('Number of employees: '))
salary = {}
for i in range(n):
    name = input('Name: ')
    salary[name] = int(input('Salary: '))
print(salary)
print('Total salary bill:', sum(salary.values()))
for name, s in salary.items():
    if s > 40000:
        print(name, 'earns more than 40000')
Number of employees: 3 Name: Ravi Salary: 38000 Name: Meena Salary: 52000 Name: Joseph Salary: 41000 {'Ravi': 38000, 'Meena': 52000, 'Joseph': 41000} Total salary bill: 131000 Meena earns more than 40000 Joseph earns more than 40000

3. Dictionary comprehension and zip()

Python
fruits = ['apple', 'mango', 'kiwi']
lengths = {f: len(f) for f in fruits}     # dictionary comprehension
print(lengths)
print(dict(zip(['a', 'b', 'c'], [1, 2, 3])))
{'apple': 5, 'mango': 5, 'kiwi': 4} {'a': 1, 'b': 2, 'c': 3}

Nested dictionaries

A value can itself be a dictionary or list — this is how real records (JSON data from websites and apps) look.

Python
students = {
    101: {'name': 'Asha', 'marks': [78, 85, 90]},
    102: {'name': 'Dev', 'marks': [66, 72, 58]},
}
for roll, info in students.items():
    avg = sum(info['marks']) / len(info['marks'])
    print(roll, info['name'], round(avg, 2))
101 Asha 84.33 102 Dev 65.33

Summary & practice

  • Dictionary = unique keys mapped to values in { }; mutable.
  • Access with d[k] or d.get(k); add/modify with d[k] = v; delete with del, pop.
  • Traverse with items(); methods keys, values, update, popitem.
  • Counting pattern: d[x] = d.get(x, 0) + 1.
✅ Practice

1) Store the monthly electricity units of a house for 6 months and print the month with the highest use. 2) Count how many times each word appears in a sentence. 3) Create a dictionary of 5 products and their prices, and print products costing more than ₹100.

Frequently Asked Questions

Why is a dictionary useful in data handling?
Real data often comes as labelled values — a student’s name, roll and marks, or a product’s code and price. A dictionary keeps each value with its label (key), so it is easy to read and fast to look up.
Are dictionary keys case-sensitive?
Yes. "Maths" and "maths" are different keys.
What does items() return?
A view of (key, value) pairs, ideal for a for loop like: for k, v in d.items().
← Class 11 Informatics Practices
🔗

Share this topic with a friend

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

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

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

Next topicUnderstanding Data: Collect, Store, Process Your progress: 9 / 20 (45%) · Lesson 10 / 20 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