|

Dictionaries in Python Notes – Class 11 CS (083) | CBSE Revision

These Dictionaries in Python notes not only provide excellent concept clarity but also support practical learning through examples and programming-based explanations. Fully aligned with the latest CBSE curriculum of Class 11 Computer Science, they cover all the essential topics you need for theory, revision, and practical preparation.

Introduction to Dictionaries

  • A dictionary is a data type that stores data in the form of key-value pairs.
  • It falls under the category of mapping data types because it maps a key to a value.
  • A key-value pair is called an item.
  • A colon ( : ) separates the key and value.
  • Multiple items are separated by commas ( , ).
  • Dictionaries are enclosed within curly braces { }.
  • Dictionary items are unordered, so the output order may differ from the order of insertion.

Creating a Dictionary

  • A dictionary is created by enclosing items within curly braces { }.
  • Each item in a dictionary is written as a key : value pair.
  • Keys must be unique and of immutable data types such as: Number, String, Tuple
  • Values can be of any data type and may be repeated.

Example 1: Empty Dictionary Using Curly Braces

dict1 = {}
print(dict1)

Output
{}

Example 2: Empty Dictionary Using dict()

dict2 = dict()
print(dict2)

Output
{}

Example 3: Dictionary with Data

# product_price stores product names
# and their prices
product_price = {
    ‘Laptop’: 55000,
    ‘Mobile’: 18000,
    ‘Tablet’: 25000,
    ‘Printer’: 12000
}
print(product_price)

Output
{‘Laptop’: 55000, ‘Mobile’: 18000, ‘Tablet’: 25000, ‘Printer’: 12000}

Accessing Items in a Dictionary

  • In a dictionary, items are accessed using their keys instead of indices.
  • Each key acts like an index.
  • A key maps directly to its corresponding value.
  • If the key exists, Python returns its value, otherwise shows a KeyError.

Example: Accessing Dictionary Items

# Dictionary storing city names and temperatures
weather = {
    ‘Delhi’: 38,
    ‘Mumbai’: 32,
    ‘Chennai’: 35,
    ‘Kolkata’: 34
}

# Accessing values using keys
print(weather[‘Mumbai’])
print(weather[‘Chennai’])

Output:
32
35

Example: Accessing a Non-Existing Key

print(weather[‘Pune’])

Output:
KeyError: ‘Pune’

Dictionaries are Mutable

A dictionary is a mutable data type.
This means the contents of a dictionary can be changed after it is created.
We can:

  • Add new items
  • Modify existing items
  • Delete items from a dictionary

Adding a New Item in Dictionary

A new key-value pair can be added by assigning a value to a new key.

Example

# Dictionary storing employee salaries
salary = {
    ‘Aman’: 25000,
    ‘Riya’: 30000,
    ‘Kunal’: 28000
}

# Adding a new item
salary[‘Neha’] = 32000
print(salary)

Output

{‘Aman’: 25000, ‘Riya’: 30000, ‘Kunal’: 28000, ‘Neha’: 32000}

Modifying an Existing Item in Dictionary

An existing item can be modified by assigning a new value to its key.

Example

# Dictionary storing employee salaries

salary = {
    ‘Aman’: 25000,
    ‘Riya’: 30000,
    ‘Kunal’: 28000
}

# Modifying salary of Kunal
salary[‘Kunal’] = 35000
print(salary)

Output
{‘Aman’: 25000, ‘Riya’: 30000, ‘Kunal’: 35000}

Dictionary Operations

Membership Operators in Dictionary

Membership operators are used to check whether a key exists in a dictionary or not.

  • in returns True if the key is present in the dictionary.
  • not in returns True if the key is not present in the dictionary.

Example

# Dictionary storing fruit prices
fruits = {
    ‘Apple’: 120,
    ‘Banana’: 40,
    ‘Mango’: 90,
    ‘Orange’: 80
}

# Using in operator
print(‘Mango’ in fruits)

# Using not in operator
print(‘Grapes’ not in fruits)

Output
True
True

Traversing a Dictionary

  • Traversing a dictionary means accessing each item of the dictionary one by one.
  • A dictionary can be traversed using a for loop.

Method 1: Traversing Using Keys

In this method, the loop accesses each key of the dictionary. The corresponding value is accessed using the key.

Example

# Dictionary storing player scores
scores = {
    ‘Rohit’: 75,
    ‘Virat’: 82,
    ‘Dhoni’: 68,
    ‘Rahul’: 91
}
for key in scores:
    print(key, ‘:’, scores[key])

Output:
Rohit : 75
Virat : 82
Dhoni : 68
Rahul : 91

Method 2: Traversing Using items()

The items() method returns both keys and values together.

Example

# Traversing dictionary using items()
for key, value in scores.items():
    print(key, ‘:’, value)

Output
Rohit : 75
Virat : 82
Dhoni : 68
Rahul : 91

Dictionary Methods

Method / FunctionDescriptionExample
len()Returns the number of key-value pairs in a dictionarystudents = {‘Aman’:78, ‘Riya’:85, ‘Neha’:90} print(len(students)) Output: 3
dict()Creates a dictionary from key-value pairspair_list = [(‘Pen’,20), (‘Pencil’,10)] items = dict(pair_list) print(items) Output: {‘Pen’: 20, ‘Pencil’: 10}
keys()Returns all keys of the dictionaryemployee = {‘Amit’:25000, ‘Neha’:30000} print(employee.keys()) Output: dict_keys([‘Amit’, ‘Neha’])
values()Returns all values of the dictionaryemployee = {‘Amit’:25000, ‘Neha’:30000} print(employee.values()) Output: dict_values([25000, 30000])
items()Returns key-value pairs as tuplesemployee = {‘Amit’:25000, ‘Neha’:30000} print(employee.items()) Output: dict_items([(‘Amit’, 25000), (‘Neha’, 30000)])
get()Returns the value of the given key. Returns None if key is absentemployee = {‘Amit’:25000, ‘Neha’:30000} print(employee.get(‘Neha’)) print(employee.get(‘Riya’)) Output: 30000 None
update()Adds items of one dictionary into anotherdict1 = {‘Apple’:120} dict2 = {‘Mango’:90} dict1.update(dict2) print(dict1) Output: {‘Apple’: 120, ‘Mango’: 90}
fromkeys()Creates a dictionary with specified keys and a common valuekeys = (‘Maths’, ‘Science’, ‘English’) marks = dict.fromkeys(keys, 0) print(marks) Output: {‘Maths’: 0, ‘Science’: 0, ‘English’: 0}
copy()Returns a copy of the dictionarydict1 = {‘A’:10, ‘B’:20} dict2 = dict1.copy() print(dict2) Output: {‘A’: 10, ‘B’: 20}
pop()Removes the specified key and returns its valuemarks = {‘Maths’:95, ‘Science’:88} x = marks.pop(‘Science’) print(x) print(marks) Output: 88 {‘Maths’: 95}
popitem()Removes and returns the last inserted key-value pairdata = {‘A’:1, ‘B’:2, ‘C’:3} print(data.popitem()) print(data) Output: (‘C’, 3) {‘A’: 1, ‘B’: 2}
setdefault()Returns the value of the key. If key is absent, inserts the key with the specified valuestudent = {‘Aman’:90, ‘Riya’:85} print(student.setdefault(‘Riya’, 80)) print(student.setdefault(‘Neha’, 75)) print(student) Output: 85 75 {‘Aman’: 90, ‘Riya’: 85, ‘Neha’: 75}
delDeletes an item using its keymarks = {‘Maths’:95, ‘Science’:88} del marks[‘Science’] print(marks) Output: {‘Maths’: 95}
clear()Removes all items from the dictionarymarks = {‘Maths’:95, ‘Science’:88} marks.clear() print(marks) Output: {}
max()Returns the maximum key in the dictionarydata = {‘A’:10, ‘C’:30, ‘B’:20} print(max(data)) Output: C
min()Returns the minimum key in the dictionarydata = {‘A’:10, ‘C’:30, ‘B’:20} print(min(data)) Output: A
sorted()Returns the sorted list of keys of the dictionarydata = {‘C’:30, ‘A’:10, ‘B’:20} print(sorted(data)) Output: [‘A’, ‘B’, ‘C’]

Dictionary Programs in Python – Manipulating Dictionary

Count the Frequency of Characters in a String Using Dictionary

# Program to count frequency of characters
text = input(“Enter a string: “)
freq = {}
for ch in text:
    if ch in freq:
        freq[ch] += 1
    else:
        freq[ch] = 1
print(“Character Frequency:”)
print(freq)

Sample Output

Enter a string: hello
Character Frequency:
{‘h’: 1, ‘e’: 1, ‘l’: 2, ‘o’: 1}

Create a Dictionary of Employee Names and Salaries

# Dictionary storing employee salaries
employee = {
    ‘Aman’: 25000,
    ‘Riya’: 30000,
    ‘Karan’: 28000,
    ‘Neha’: 35000
}

# Accessing salary using employee name
name = input(“Enter employee name: “)
if name in employee:
    print(“Salary =”, employee[name])
else:
    print(“Employee not found”)

Sample Output

Enter employee name: Neha
Salary = 35000

Program 3: Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is the decimal number and the value is the corresponding number in words. Perform the following operations on this dictionary:

  1. Display the keys
  2. Display the values
  3. Display the items
  4. Find the length of the dictionary
  5. Check if 7 is present or not
  6. Check if 2 is present or not
  7. Retrieve the value corresponding to the key 9
  8. Delete the item from the dictionary corresponding to the key 9

# Creating dictionary of odd numbers
ODD = {
    1: ‘One’,
    3: ‘Three’,
    5: ‘Five’,
    7: ‘Seven’,
    9: ‘Nine’
}
print(“Dictionary:”)
print(ODD)
# (a) Display the keys
print(“\nKeys:”)
print(ODD.keys())

# (b) Display the values
print(“\nValues:”)
print(ODD.values())

# (c) Display the items
print(“\nItems:”)
print(ODD.items())

# (d) Find the length of dictionary
print(“\nLength of Dictionary:”)
print(len(ODD))

# (e) Check if 7 is present
print(“\nIs 7 present?”)
print(7 in ODD)

# (f) Check if 2 is present
print(“\nIs 2 present?”)
print(2 in ODD)

# (g) Retrieve value corresponding to key 9
print(“\nValue of key 9:”)
print(ODD.get(9))

# (h) Delete item with key 9
del ODD[9]

print(“\nDictionary after deleting key 9:”)
print(ODD)

Sample Output

Dictionary:
{1: ‘One’, 3: ‘Three’, 5: ‘Five’, 7: ‘Seven’, 9: ‘Nine’}

Keys:
dict_keys([1, 3, 5, 7, 9])

Values:
dict_values([‘One’, ‘Three’, ‘Five’, ‘Seven’, ‘Nine’])

Items:
dict_items([(1, ‘One’), (3, ‘Three’), (5, ‘Five’), (7, ‘Seven’), (9, ‘Nine’)])

Length of Dictionary:
5

Is 7 present?
True

Is 2 present?
False

Value of key 9:
Nine

Dictionary after deleting key 9:
{1: ‘One’, 3: ‘Three’, 5: ‘Five’, 7: ‘Seven’}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *