Dictionaries and its Methods

1. 📖 Dictionaries

    1.1 What is a Dictionary?
    1. 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"}
    1.2 Creating Dictionaries
    1. 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)
    1.3 Keys and Values
    1. 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"
    1.4 Rules for Keys and Values
    1. 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.
    1.5 Keys Must Be Unique
    1. 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.
    1.6 Duplicate Keys
    1. 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.

2. 🔎 Accessing and Updating Dictionary Data

    2.1 Accessing Value using Key [ ]
    1. We can access a value using its key. Example: course_info = {"name": "Python Basics", "duration": 40, "instructor": "Rabindra"}print(course_info["name"]) # ➜ Python Basics print(course_info["duration"]) # ➜ 40 📌 In dictionaries, we use keys instead of indexes.
    2.2 KeyError while Accessing Missing Key
    1. 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.
    2.3 Accessing Value using get()
    1. 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 Basics print(course_info.get("level")) # ➜ None
    2.4 get() with Default Value
    1. 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")) # ➜ Beginner print(course_info.get("duration", 0)) # ➜ 40
    2.5 Adding New Key-Value Pair
    1. 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"}
    2.6 Updating Existing Value
    1. If the key already exists, assigning a new value updates it. Example: course_info = {"name": "Python Basics", "duration": 40}course_info["duration"] = 45 print(course_info) # ➜ {"name": "Python Basics", "duration": 45}

3. 📋 Dictionary Keys, Values, Items, and Membership

    3.1 keys()
    1. 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"])
    3.2 values()
    1. 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"])
    3.3 items()
    1. 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")])
    3.4 Membership using in
    1. The in operator checks whether a key is present in the dictionary. Example: student_info = {"name": "Ram", "age": 22, "grade": "A"}print("name" in student_info) # ➜ True print("address" in student_info) # ➜ False 📌 in checks keys, not values.
    3.5 Checking Values
    1. To check whether a value exists, use values(). Example: student_info = {"name": "Ram", "age": 22, "grade": "A"}print("Ram" in student_info.values()) # ➜ True print("Kathmandu" in student_info.values()) # ➜ False

4. ➕➖ Updating, Removing, and Copying Dictionaries

    4.1 update()
    1. 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"}
    4.2 pop()
    1. 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) # ➜ 22 print(student_info) # ➜ {"name": "Ram", "grade": "A"}
    4.3 pop() with Missing Key
    1. 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.
    4.4 len()
    1. 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)) # ➜ 3
    4.5 copy()
    1. copy() 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}
    4.6 Assignment is Not Copy
    1. 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} 📌 Use copy() when you want a separate dictionary.

5. 🧩 Nested Dictionaries

    5.1 What is a Nested Dictionary?
    1. 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)
    5.2 Accessing Nested Dictionary Data
    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"]) # ➜ 3 print(college_1["java"]["type"]) # ➜ medium
    5.3 Updating Nested Dictionary
    1. Example: college_1 = { "python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"} }college_1["python"]["type"] = "advanced" print(college_1)
    5.4 Merging Course Dictionaries
    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)

6. 🔢 Useful Helper: range()

    6.1 What is range()?
    1. 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.
    6.2 range() Examples
    1. 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]

7. 📊 Collection Data Comparison

    7.1 Comparing Python Collection Data Types
    1. 📌 Lists and tuples use indexes. 📌 Sets are used for unique items. 📌 Dictionaries are used for key-value data.
Comparison of Collection Data Types
PropertyListTupleSetDictionary
OrderedYesYesNoYes, in modern Python
MutableYesNoYesYes
Allows duplicatesYesYesNoKeys must be unique, values can repeat
Accessed byIndexIndexMembership, not indexKey
Comparison of collection data types

Practice QuestionsNot started

  1. 1. Creating and Accessing Dictionary

    Question 1 of 7

      1.1 Create student_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}
      1. Display the student's name.
      2. Display the student's age.
      3. Display the student's grade.
      4. Display the courses enrolled.
      5. Display output in this format: Ram is 22 years old and got grade A.
      6. Access a missing key "address" using get().
      7. Access "address" using get() with default value "Not available".
  2. 2. Updating Dictionary

    Question 2 of 7

      2.1 Use student_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}
      1. Update student's grade to "A+" and display updated dictionary.
      2. Add "level" key with value "Beginner" and display updated dictionary.
      3. Add one more course "Python" to student's courses and display updated dictionary.
      4. Remove age from student information and display updated dictionary.
      5. Display total number of key-value pairs in student_info.
  3. 3. Keys, Values, Items, and Membership

    Question 3 of 7

      3.1 Use student_info = {"name": "Ram", "age": 22, "grade": "A", "courses": ["DS", "SQL"]}
      1. Display all keys.
      2. Display all values.
      3. Display all key-value pairs.
      4. Check if "address" key is present in student_info.
      5. Check if "grade" key is present in student_info.
      6. Check if "Ram" is present in dictionary values.
      7. Check if "Kathmandu" is present in dictionary values.
  4. 4. Copying Dictionary

    Question 4 of 7

      4.1 Use student_info = {"name": "Ram", "age": 22, "grade": "A"}
      1. Create a copy of student_info.
      2. Update copied dictionary name to "Bob".
      3. Update copied dictionary grade to "B".
      4. Display original dictionary.
      5. Display copied dictionary.
      6. Assign student_info to another variable using =.
      7. Update age using the new variable.
      8. Display both dictionaries and observe the result.
  5. 5. Nested Dictionary

    Question 5 of 7

      5.1 Create college_1 = {"python": {"duration": 3, "type": "basic"}, "java": {"duration": 4, "type": "medium"}} and college_2 = {"multimedia": {"duration": 2, "type": "basic"}, "javascript": {"duration": 5, "type": "advanced"}}
      1. Display python course details.
      2. Display python course duration.
      3. Display java course type.
      4. Update python course type to "advanced".
      5. College_1 acquired College_2. Update College_1 courses with College_2 courses.
      6. Display updated College_1 dictionary.
  6. 6. Translation Dictionary

    Question 6 of 7

      6.1 Create translation_dict = {"hello": "hola", "thank you": "gracias", "goodbye": "adios"}
      1. Ask user to input a word in English.
      2. Display its Spanish translation.
      3. If word is not found, display: Translation not found
  7. 7. range() Practice

    Question 7 of 7

      7.1 Practice range() tasks:
      1. Generate and display a list of numbers from 0 to 4.
      2. Generate and display a list of numbers from 1 to 5.
      3. Generate and display even numbers from 0 to 20.
      4. Generate and display multiples of 3 from 3 to 30.
      5. Generate and display numbers from 30 to 1 in descending order with step 3.