Dictionaries and its Methods
✕1. 📖 Dictionaries
- Imagine a real dictionary. A word is used to find its meaning.
For Example:
apple ➜ a fruit
book ➜ something we read
pen ➜ something we write with
A Python dictionary works in a similar way. In Python:
Key ➜ works like the word
Value ➜ works like the meaning or information
A dictionary is a data type in Python used to store data in key-value pairs. It is used to look up values using keys instead of indexes.
A dictionary is:
✅ Ordered in modern Python
✅ Mutable
✅ Written inside curly braces
{ }✅ Stores data as key-value pairs ✅ Uses keys instead of indexes ✅ Keys must be unique ✅ Values can be repeated 👉 Key means the label used to identify data. 👉 Value means the data stored for that key. 👉 Mutable means we can add, update, or remove key-value pairs after the dictionary is created. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print(student_info)# ➜ {"name": "Ram", "age": 22, "grade": "A"} - Dictionaries are created by placing key-value pairs inside curly braces
{ }. Each key and value are separated by colon:. Each key-value pair is separated by comma,. Syntax:dictionary_name = {key_1: value_1, key_2: value_2}Examples:student_info = {"name": "Ram", "age": 22, "grade": "A"}course_info = {"name": "Python Basics", "duration": 40, "instructor": "Rabindra"}empty_dict = {}print(student_info)print(course_info)print(empty_dict) - Keys are used to identify values.
Example:
student_info = { "name": "Ram", "age": 22, "grade": "A" }Here: Key ➜ "name" Value ➜ "Ram" Key ➜ "age" Value ➜ 22 Key ➜ "grade" Value ➜ "A" - Dictionary keys must be: Unique, Immutable
This means keys can be: Strings, Numbers, Tuples
Values can be any data type.
Example:
my_dict = { "name": "Rabindra", 1: "one", (2, 3): "tuple key", "marks": [80, 90, 85] }print(my_dict)📌 Lists cannot be used as dictionary keys because lists are mutable. - In a real dictionary, one word is usually written once. Similarly, in a Python dictionary, one key must be unique. But values can be repeated.
Example:
student_marks = {"Ram": 80, "Hari": 80, "Sita": 90}print(student_marks)Here: "Ram", "Hari", and "Sita" are unique keys. But the value 80 is repeated. - If the same key is written more than once, the latest value is kept.
Example:
student = {"name": "Ram", "name": "Hari"}print(student)# ➜ {"name": "Hari"} 📌 The key "name" appeared twice, so the latest value "Hari" is kept.
1.1 What is a Dictionary?
1.2 Creating Dictionaries
1.3 Keys and Values
1.4 Rules for Keys and Values
1.5 Keys Must Be Unique
1.6 Duplicate Keys
2. 🔎 Accessing and Updating Dictionary Data
- We can access a value using its key.
Example:
course_info = {"name": "Python Basics", "duration": 40, "instructor": "Rabindra"}print(course_info["name"])# ➜ Python Basicsprint(course_info["duration"])# ➜ 40 📌 In dictionaries, we use keys instead of indexes. - If we use
[ ]with a key that does not exist, Python gives an error. Example:course_info = {"name": "Python Basics", "duration": 40}print(course_info["level"])# ➜ KeyError ⚠️ This line gives an error because "level" key is not found. 📌 KeyError means Python could not find the requested key in the dictionary. get()is used to access a value safely. It does not give an error if the key is not found. Example:course_info = {"name": "Python Basics", "duration": 40}print(course_info.get("name"))# ➜ Python Basicsprint(course_info.get("level"))# ➜ None- We can give a default value to
get(). If the key is not found, the default value is returned. Example:course_info = {"name": "Python Basics", "duration": 40}print(course_info.get("level", "Beginner"))# ➜ Beginnerprint(course_info.get("duration", 0))# ➜ 40 - We can add a new key-value pair using
[ ]. Example:course_info = {"name": "Python Basics", "duration": 40}course_info["level"] = "Beginner"print(course_info)# ➜ {"name": "Python Basics", "duration": 40, "level": "Beginner"} - If the key already exists, assigning a new value updates it.
Example:
course_info = {"name": "Python Basics", "duration": 40}course_info["duration"] = 45print(course_info)# ➜ {"name": "Python Basics", "duration": 45}
2.1 Accessing Value using Key [ ]
2.2 KeyError while Accessing Missing Key
2.3 Accessing Value using get()
2.4 get() with Default Value
2.5 Adding New Key-Value Pair
2.6 Updating Existing Value
3. 📋 Dictionary Keys, Values, Items, and Membership
keys()returns all keys from a dictionary. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print(student_info.keys())# ➜ dict_keys(["name", "age", "grade"])values()returns all values from a dictionary. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print(student_info.values())# ➜ dict_values(["Ram", 22, "A"])items()returns all key-value pairs from a dictionary. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print(student_info.items())# ➜ dict_items([("name", "Ram"), ("age", 22), ("grade", "A")])- The
inoperator checks whether a key is present in the dictionary. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print("name" in student_info)# ➜ Trueprint("address" in student_info)# ➜ False 📌inchecks keys, not values. - To check whether a value exists, use
values(). Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print("Ram" in student_info.values())# ➜ Trueprint("Kathmandu" in student_info.values())# ➜ False
3.1 keys()
3.2 values()
3.3 items()
3.4 Membership using in
3.5 Checking Values
4. ➕➖ Updating, Removing, and Copying Dictionaries
update()is used to add or update key-value pairs from another dictionary. If a key already exists, its value is updated. If a key does not exist, a new key-value pair is added. Example:student_info = {"name": "Ram", "age": 22}update_info = {"age": 23, "city": "Kathmandu"}student_info.update(update_info)print(student_info)# ➜ {"name": "Ram", "age": 23, "city": "Kathmandu"}pop()removes a key from the dictionary and returns its value. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}removed_value = student_info.pop("age")print(removed_value)# ➜ 22print(student_info)# ➜ {"name": "Ram", "grade": "A"}- If the key is not found,
pop()gives an error. Example:student_info = {"name": "Ram", "age": 22}student_info.pop("address")# ➜ KeyError ⚠️ This line gives an error because "address" key is not found. 📌 KeyError means Python could not find the requested key in the dictionary. len()is used to count the number of key-value pairs in a dictionary. Example:student_info = {"name": "Ram", "age": 22, "grade": "A"}print(len(student_info))# ➜ 3copy()creates a copy of a dictionary. This is useful when we want to modify the copied dictionary without changing the original dictionary. Example:original_dict = {"name": "Ram", "age": 22}copied_dict = original_dict.copy()copied_dict["name"] = "Bob"print(original_dict)# ➜ {"name": "Ram", "age": 22}print(copied_dict)# ➜ {"name": "Bob", "age": 22}- If we assign one dictionary to another variable using
=, both variables refer to the same dictionary. Example:original_dict = {"name": "Ram", "age": 22}same_dict = original_dictsame_dict["age"] = 25print(original_dict)# ➜ {"name": "Ram", "age": 25}print(same_dict)# ➜ {"name": "Ram", "age": 25} 📌 Usecopy()when you want a separate dictionary.
4.1 update()
4.2 pop()
4.3 pop() with Missing Key
4.4 len()
4.5 copy()
4.6 Assignment is Not Copy
5. 🧩 Nested Dictionaries
- Imagine a college course catalog. Each course has its own group of details.
Example:
Python ➜ duration: 3, type: basic
Java ➜ duration: 4, type: medium
A nested dictionary can store this kind of grouped data. A dictionary inside another dictionary is called a nested dictionary. Nested dictionaries are useful when one item has multiple details.
Example:
college_1 = { "python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"} }print(college_1) - To access data from a nested dictionary, we use multiple keys.
Example:
college_1 = { "python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"} }print(college_1["python"])# ➜ {"duration": 3, "type": "basic"}print(college_1["python"]["duration"])# ➜ 3print(college_1["java"]["type"])# ➜ medium - Example:
college_1 = { "python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"} }college_1["python"]["type"] = "advanced"print(college_1) - Example:
college_1 = { "python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"} }college_2 = { "multimedia": {"duration": 2, "type": "basic"}, "javascript": {"duration": 5, "type": "advanced"} }college_1.update(college_2)print(college_1)
5.1 What is a Nested Dictionary?
5.2 Accessing Nested Dictionary Data
5.3 Updating Nested Dictionary
5.4 Merging Course Dictionaries
6. 🔢 Useful Helper: range()
- Imagine numbering seats in a row:
0, 1, 2, 3, 4
Or counting down before a rocket launch:
10, 9, 8, 7, 6, ...
range() generates this kind of number sequence.
range()is used to generate a sequence of numbers. It is commonly used when we need numbers in a specific pattern. 📌 range() is often used later with loops to repeat actions a set number of times. Syntax:range(start, stop, step)start ➜ Starting number, included stop ➜ Stopping number, not included step ➜ Difference between numbers 📌 start is optional. 📌 step is optional. 📌 stop is not included. print(list(range(5)))# ➜ [0, 1, 2, 3, 4]print(list(range(1, 6)))# ➜ [1, 2, 3, 4, 5]print(list(range(0, 10, 2)))# ➜ [0, 2, 4, 6, 8]print(list(range(10, 0, -1)))# ➜ [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
6.1 What is range()?
6.2 range() Examples
7. 📊 Collection Data Comparison
- 📌 Lists and tuples use indexes. 📌 Sets are used for unique items. 📌 Dictionaries are used for key-value data.
7.1 Comparing Python Collection Data Types
Comparison of Collection Data Types
| Property | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | Yes, in modern Python |
| Mutable | Yes | No | Yes | Yes |
| Allows duplicates | Yes | Yes | No | Keys must be unique, values can repeat |
| Accessed by | Index | Index | Membership, not index | Key |
Comparison of collection data types
Practice QuestionsNot started
1. Creating and Accessing Dictionary
Question 1 of 7
- Display the student's name.
- Display the student's age.
- Display the student's grade.
- Display the courses enrolled.
- Display output in this format:
Ram is 22 years old and got grade A. - Access a missing key "address" using
get(). - Access "address" using
get()with default value "Not available".
1.1 Createstudent_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}2. Updating Dictionary
Question 2 of 7
- Update student's grade to "A+" and display updated dictionary.
- Add "level" key with value "Beginner" and display updated dictionary.
- Add one more course "Python" to student's courses and display updated dictionary.
- Remove age from student information and display updated dictionary.
- Display total number of key-value pairs in
student_info.
2.1 Usestudent_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}3. Keys, Values, Items, and Membership
Question 3 of 7
- Display all keys.
- Display all values.
- Display all key-value pairs.
- Check if "address" key is present in
student_info. - Check if "grade" key is present in
student_info. - Check if "Ram" is present in dictionary values.
- Check if "Kathmandu" is present in dictionary values.
3.1 Usestudent_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}4. Copying Dictionary
Question 4 of 7
- Create a copy of
student_info. - Update copied dictionary name to "Bob".
- Update copied dictionary grade to "B".
- Display original dictionary.
- Display copied dictionary.
- Assign
student_infoto another variable using=. - Update age using the new variable.
- Display both dictionaries and observe the result.
4.1 Usestudent_info = {"name": "Ram", "age": 22, "grade": "A"}- Create a copy of
5. Nested Dictionary
Question 5 of 7
- Display python course details.
- Display python course duration.
- Display java course type.
- Update python course type to "advanced".
- College_1 acquired College_2. Update College_1 courses with College_2 courses.
- Display updated College_1 dictionary.
5.1 Createcollege_1 = {"python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"}}andcollege_2 = {"multimedia": {"duration": 2, "type": "basic"}, "javascript": {"duration": 5, "type": "advanced"}}6. Translation Dictionary
Question 6 of 7
- Ask user to input a word in English.
- Display its Spanish translation.
- If word is not found, display:
Translation not found
6.1 Createtranslation_dict = {"hello": "hola", "thank you": "gracias", "goodbye": "adios"}7. range() Practice
Question 7 of 7
- Generate and display a list of numbers from 0 to 4.
- Generate and display a list of numbers from 1 to 5.
- Generate and display even numbers from 0 to 20.
- Generate and display multiples of 3 from 3 to 30.
- Generate and display numbers from 30 to 1 in descending order with step 3.
7.1 Practice range() tasks:
