Dictionary in Python

Dictionary in Python: Class 11th

1. Introduction to Dictionary

  • A dictionary in Python is an unordered collection of key–value pairs.
  • Each value is accessed using its key, not by index.
  • Syntax: dictionary_name = {key1: value1, key2: value2, ...}
  • Example: student = {"name": "Aarav", "age": 16, "class": 11}

Characteristics of a Dictionary

  • Keys are unique (no duplicates).
  • Keys must be immutable (string, number, tuple).
  • Values can be of any data type (list, string, number, etc.).
  • Dictionaries are mutable (can be changed after creation).

2. Accessing Items in a Dictionary Using Keys

Values can be accessed using:

(a) Square brackets

student["name"]   # Output: Aarav

If key is not present, it gives an error.

(b) get() method

student.get("age")    # Output: 16
student.get("address", "Not Found")   # Safe access

Does not cause an error if the key is missing.


3. Mutability of a Dictionary

Dictionaries are mutable, meaning they can be added, modified, or deleted.

(a) Adding a New Item

student["grade"] = "A"     # Adds new key–value pair

(b) Modifying an Existing Item

student["age"] = 17        # Modifies existing value

4. Traversing a Dictionary

You can iterate over:

(a) Keys (default)

for k in student:
    print(k, student[k])

(b) Values

for v in student.values():
    print(v)

(c) Key–Value pairs

for k, v in student.items():
    print(k, v)

5. Built-in Dictionary Functions and Methods

Function/MethodDescriptionExample
len()Returns the number of itemslen(student)
dict()Creates a new dictionaryd = dict(a=1, b=2)
keys()Returns all keysstudent.keys()
values()Returns all valuesstudent.values()
items()Returns key-value pairsstudent.items()
get()Returns value of a keystudent.get("name")
update()Updates dictionarystudent.update({"age": 18})
delDeletes a key/value pairdel student["class"]
clear()Removes all itemsstudent.clear()
fromkeys()Used to create a new dictionary from a sequence of keys and an optional default value.dict.fromkeys(["a","b"], 0)
copy()Creates shallow copynew = student.copy()
pop()Removes key and returns valuestudent.pop("age")
popitem()Removes last inserted itemstudent.popitem()
setdefault()Returns the corresponding value if the specified key present else
inserts a key with a default value: 
If default_value is not explicitly provided, it defaults to None.
student.setdefault("section", "B")
max()Returns max keymax(student)
min()Returns min keymin(student)
sorted()Returns sorted list of keyssorted(student)

Here are simple and clear explanations of copy(), pop(), and popitem() methods in a Python dictionary.

1. copy()

Creates a shallow copy of the dictionary (a new dictionary with the same key–value pairs). It make a duplicate dictionary without changing the original. If you modify new_student, the original student dictionary does not change.

Example:

student = {"name": "Amit", "age": 17}
new_student = student.copy()

print(new_student)

Output:

{'name': 'Amit', 'age': 17}

2. pop()

Removes the key that you specify and returns its value.

Syntax:

dictionary.pop(key)

Features:

  • You must specify the key.
  • If the key does not exist → KeyError (unless default value is given).

Example:

student = {"name": "Amit", "age": 17, "class": 11}

value = student.pop("age")

print(value)        # Output: 17
print(student)      # Output: {'name': 'Amit', 'class': 11}

3. popitem()

Removes and returns the last inserted key–value pair in tuple form (key, value). This is used when you want to delete items in the same order they were added.

Example:

student = {"name": "Amit", "age": 17, "class": 11}

last_item = student.popitem()

print(last_item)    # Output: ('class', 11)
print(student)      # Output: {'name': 'Amit', 'age': 17}


6. Suggested Programs

Program 1: Count number of times each character appears in a string

string = "banana"
freq = {}

for ch in string:
    if ch in freq:
        freq[ch] += 1
    else:
        freq[ch] = 1

print("Character Frequency:", freq)

Output:

{'b': 1, 'a': 3, 'n': 2}

Program 2: Create a dictionary with names of employees and salary; access them

employees = {
    "Rohit": 45000,
    "Ananya": 52000,
    "Mehul": 48000
}

# Access salary of an employee
print("Salary of Ananya:", employees["Ananya"])

# Traversing all employees
for name, salary in employees.items():
    print(name, "→", salary)

Output:

Salary of Ananya: 52000
Rohit → 45000
Ananya → 52000
Mehul → 48000

Summary:

  • Dictionary = key-value pairs, mutable, unordered.
  • Access values using [] or get().
  • Modify or add items directly using assignment.
  • Supports many built-in methods like keys(), values(), items(), update(), pop(), etc.
  • Useful for counting, mapping names to data, and storing structured information.

MCQs on Dictionary (Class 11)

1. A dictionary in Python stores data in the form of:

A. Indexed values
B. Key–value pairs
C. Only numeric values
D. Immutable elements


2. Which of the following is a valid dictionary?

A. {1, 2, 3}
B. (1: "one", 2: "two")
C. {"name": "Amit", "age": 17}
D. ["a": 1, "b": 2]


3. Dictionary keys must be:

A. Mutable
B. Unique
C. Duplicates allowed
D. Lists


4. Which method is used to get all keys of a dictionary?

A. values()
B. get()
C. keys()
D. items()


5. What will student.get("name") return if key "name" exists?

A. Error
B. None
C. Value of “name”
D. 0


6. Which operator is used to access dictionary values?

A. ()
B. []
C. {}
D. <>


7. pop() method removes:

A. Any random item
B. Last inserted item
C. An item with the specified key
D. All items


8. popitem() removes:

A. All items
B. First item
C. Last inserted key–value pair
D. A key chosen by the user


9. To delete a specific key from a dictionary, we use:

A. remove
B. del
C. erase
D. delete


10. What will be the output of: len({"a":1,"b":2,"c":3}) ?

A. 1
B. 2
C. 3
D. 6


11. Which method returns key–value pairs as tuples?

A. items()
B. keys()
C. values()
D. tuple()


12. dict.fromkeys(["a","b"], 0) returns:

A. {"a":0, "b":0}
B. {0:"a", 0:"b"}
C. ["a","b"]
D. {"a":[], "b":[]}


13. Which of the following will modify value of key “age”?

A. age = student["age"]
B. student["age"] = 18
C. update["age":18]
D. student.update("age",18)


14. Which method adds another dictionary to the current dictionary?

A. add()
B. insert()
C. update()
D. join()


15. What is the output of: sorted({"b":2, "a":1}) ?

A. [("a",1), ("b",2)]
B. ["a", "b"]
C. ["b", "a"]
D. {}


16. What will happen if we try to use a list as a dictionary key?

A. Accepted
B. Converted automatically
C. Error (lists are mutable)
D. Ignored


17. Which method clears all items from a dictionary?

A. empty()
B. clear()
C. remove()
D. erase()


18. What is the datatype of student.items() ?

A. list
B. tuple
C. dict_items
D. string


19. What does setdefault("x", 10) do?

A. Deletes “x”
B. Replaces existing “x”
C. Returns value of “x” if exists; else inserts “x”:10
D. Creates empty dictionary


20. Which function gives the maximum key in a dictionary?

A. max()
B. maxkey()
C. maximum()
D. dictmax()


Answer Key

1–B
2–C
3–B
4–C
5–C
6–B
7–C
8–C
9–B
10–C
11–A
12–A
13–B
14–C
15–B
16–C
17–B
18–C
19–C
20–A


Leave a Comment

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

Scroll to Top