Author: saqibkhan

  • Dictionary Exercises

    Dictionary Exercise 1

    Python program to create a new dictionary by extracting the keys from a given dictionary.

    Open Compiler

    d1 ={"one":11,"two":22,"three":33,"four":44,"five":55}
    keys =['two','five']
    d2={}for k in keys:
       d2[k]=d1[k]print(d2)

    It will produce the following output −

    {'two': 22, 'five': 55}
    

    Dictionary Exercise 2

    Python program to convert a dictionary to list of (k,v) tuples.

    Open Compiler

    d1 ={"one":11,"two":22,"three":33,"four":44,"five":55}
    L1 =list(d1.items())print(L1)

    It will produce the following output −

    [('one', 11), ('two', 22), ('three', 33), ('four', 44), ('five', 55)]
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Dictionary Exercise 3

    Python program to remove keys with same values in a dictionary.

    Open Compiler

    d1 ={"one":"eleven","2":2,"three":3,"11":"eleven","four":44,"two":2}
    vals =list(d1.values())#all values
    uvals =[v for v in vals if vals.count(v)==1]#unique values
    d2 ={}for k,v in d1.items():if v in uvals:
    
      d ={k:v}
      d2.update(d)print("dict with unique value:",d2)</code></pre>

    It will produce the following output −

    dict with unique value: {'three': 3, 'four': 44}
    

    Dictionary Exercise Programs

    • Python program to sort list of dictionaries by values
    • Python program to extract dictionary with each key having non-numeric value from a given dictionary.
    • Python program to build a dictionary from list of two item (k,v) tuples.
    • Python program to merge two dictionary objects, using unpack operator.
  • Dictionary Methods

    Python dictionary is an object of the built-in dict class, which defines the following methods −

    Dictionary Methods

    Sr.No.Method and Description
    1dict.clear()Removes all elements of dictionary dict.
    2dict.copy()Returns a shallow copy of dictionary dict.
    3dict.fromkeys()Create a new dictionary with keys from seq and values set to value.
    4dict.get(key, default=None)For key key, returns value or default if key not in dictionary.
    5dict.has_key(key)Returns true if a given key is available in the dictionary, otherwise it returns a false.
    6dict.items()Returns a list of dict’s (key, value) tuple pairs.
    7dict.keys()Returns list of dictionary dict’s keys.
    8dict.pop()Removes the element with specified key from the collection
    9dict.popitem()Removes the last inserted key-value pair
    10dict.setdefault(key, default=None)Similar to get(), but will set dict[key]=default if key is not already in dict.
    11dict.update(dict2)Adds dictionary dict2’s key-values pairs to dict.
    12dict.values()Returns list of dictionary dict’s values.
  •  Nested Dictionaries

    Nested Dictionaries

    Nested dictionaries in Python refer to dictionaries that are stored as values within another dictionary. In other words, a dictionary can contain other dictionaries as its values, forming a hierarchical or nested structure.

    Nested dictionaries can be modified, updated, or extended in the same way as regular dictionaries. You can add, remove, or update key-value pairs at any level of the nested structure.

    Creating a Nested Dictionary in Python

    We can create a nested dictionary in Python by defining a dictionary where the values of certain keys are themselves dictionaries. This allows for the creation of a hierarchical structure where each key-value pair represents a level of nested information. This can be achieved in several ways −

    Example: Direct Assignment

    In this approach, we can directly assign dictionaries as values to outer keys within a single dictionary definition −

    Open Compiler

    # Define the outer dictionary
    nested_dict ={"outer_key1":{"inner_key1":"value1","inner_key2":"value2"},"outer_key2":{"inner_key3":"value3","inner_key4":"value4"}}print(nested_dict)

    Example: Using a Loop

    With this method, an empty outer dictionary is initialized, and then populated with dictionaries as values using a loop to define nested dictionaries −

    Open Compiler

    # Define an empty outer dictionary
    nested_dict ={}# Add key-value pairs to the outer dictionary
    outer_keys =["outer_key1","outer_key2"]for key in outer_keys:
       nested_dict[key]={"inner_key1":"value1","inner_key2":"value2"}print(nested_dict)

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Adding Items to a Nested Dictionary in Python

    Once a nested dictionary is created, we can add items to it by accessing the specific nested dictionary using its key and then assigning a new key-value pair to it.

    Example

    In the following example, we are defining a nested dictionary “students” where each key represents a student’s name and its value is another dictionary containing details about the student.

    Then, we add a new key-value pair to Alice’s nested dictionary and add a new nested dictionary for a new student, Charlie −

    Open Compiler

    # Initial nested dictionary
    students ={"Alice":{"age":21,"major":"Computer Science"},"Bob":{"age":20,"major":"Engineering"}}# Adding a new key-value pair to Alice's nested dictionary
    students["Alice"]["GPA"]=3.8# Adding a new nested dictionary for a new student
    students["Charlie"]={"age":22,"major":"Mathematics"}print(students)

    It will produce the following output −

    {'Alice': {'age': 21, 'major': 'Computer Science', 'GPA': 3.8}, 'Bob': {'age': 20, 'major': 'Engineering'}, 'Charlie': {'age': 22, 'major': 'Mathematics'}}
    

    Accessing Items of a Nested Dictionary in Python

    Accessing items of a nested dictionary in Python refers to retrieving values stored within the nested structure by using a series of keys. Each key corresponds to a level in the hierarchy of the dictionary.

    We can achieve this through direct indexing with square brackets or by using the get() method

    Example: Using Direct Indexing

    In this approach, we access values in a nested dictionary by specifying each key in a sequence of square brackets. Each key in the sequence refers to a level in the nested dictionary, progressing one level deeper with each key −

    Open Compiler

    # Define a nested dictionary
    students ={"Alice":{"age":21,"major":"Computer Science"},"Bob":{"age":20,"major":"Engineering"},"Charlie":{"age":22,"major":"Mathematics"}}# Access Alice's major
    alice_major = students["Alice"]["major"]print("Alice's major:", alice_major)# Access Bob's age
    bob_age = students["Bob"]["age"]print("Bob's age:", bob_age)

    Following is the output of the above code −

    Alice's major: Computer Science
    Bob's age: 20
    

    Example: Using the get() Method

    The get() method is used to fetch the value associated with the specified key. If the key does not exist, it returns a default value (which is None if not specified) −

    Open Compiler

    # Define a nested dictionary
    students ={"Alice":{"age":21,"major":"Computer Science"},"Bob":{"age":20,"major":"Engineering"},"Charlie":{"age":22,"major":"Mathematics"}}# Access Alice's major using .get()
    alice_major = students.get("Alice",{}).get("major","Not Found")print("Alice's major:", alice_major)# Safely access a non-existing key using .get()
    dave_major = students.get("Dave",{}).get("major","Not Found")print("Dave's major:", dave_major)

    Output of the above code is as follows −

    Alice's major: Computer Science
    Dave's major: Not Found
    

    Deleting a Dictionary from a Nested Dictionary

    We can delete dictionaries from a nested dictionary by using the del keyword. This keyword allows us to remove a specific key-value pair from the nested dictionary.

    Example

    In the following example, we delete the nested dictionary for “Bob” from “students” dictionary using the del statement −

    Open Compiler

    # Define a nested dictionary
    students ={"Alice":{"age":21,"major":"Computer Science"},"Bob":{"age":20,"major":"Engineering"},"Charlie":{"age":22,"major":"Mathematics"}}# Delete the dictionary for Bobdel students["Bob"]# Print the updated nested dictionaryprint(students)

    We get the output as shown below −

    {'Alice': {'age': 21, 'major': 'Computer Science'}, 'Charlie': {'age': 22, 'major': 'Mathematics'}}
    

    Iterating Through a Nested Dictionary in Python

    Iterating through a nested dictionary refers to looping through the keys and values at each level of the dictionary. This allows you to access and manipulate items within the nested structure.

    We can iterate through a nested dictionary by using nested loops. The outer loop iterates over the keys and values of the main dictionary, while the inner loop iterates over the keys and values of the nested dictionaries.

    Example

    In this example, we are iterating through the “students” dictionary, retrieving each student’s name and their corresponding details by iterating through the nested dictionaries −

    Open Compiler

    # Defining a nested dictionary
    students ={"Alice":{"age":21,"major":"Computer Science"},"Bob":{"age":20,"major":"Engineering"},"Charlie":{"age":22,"major":"Mathematics"}}# Iterating through the Nested Dictionary:for student, details in students.items():print(f"Student: {student}")for key, value in details.items():print(f"  {key}: {value}")

    The output obtained is as shown below −

    Student: Alice
      age: 21
    major: Computer Science
    Student: Bob
      age: 20
      major: Engineering
    Student: Charlie
      age: 22
      major: Mathematics
  • Copy Dictionaries

    Copy Dictionaries

    Copying dictionaries in Python refers to creating a new dictionary that contains the same key-value pairs as the original dictionary.

    We can copy dictionaries using various ways, depending on the requirements and the nature of the dictionary’s values (whether they are mutable or immutable, nested or not).

    Shallow Copy

    When you perform a shallow copy, a new dictionary object is created, but it contains references to the same objects that the original dictionary references.

    This is useful when you want to duplicate the structure of a dictionary without duplicating the nested objects it contains.

    This can be done using the copy() method or the dict() function as shown below −

    Example: Using the copy() Method

    In the following example, we can see that changing the “age” in the shallow copy does not affect the original.

    However, modifying the list in the shallow copy also affects the original because the list is a mutable object and only a reference is copied.

    Open Compiler

    original_dict ={"name":"Alice","age":25,"skills":["Python","Data Science"]}
    shallow_copy = original_dict.copy()# Modifying the shallow copy
    shallow_copy["age"]=26
    shallow_copy["skills"].append("Machine Learning")print("Original dictionary:", original_dict)print("Shallow copy:", shallow_copy)

    Following is the output of the above code −

    Original dictionary: {'name': 'Alice', 'age': 25, 'skills': ['Python', 'Data Science', 'Machine Learning']}
    Shallow copy: {'name': 'Alice', 'age': 26, 'skills': ['Python', 'Data Science', 'Machine Learning']}
    

    Example: Using the dict() Method

    Similar to the copy() method, the dict() method creates a shallow copy as shown in the example below −

    Open Compiler

    original_dict ={"name":"Bob","age":30,"skills":["Java","C++"]}
    shallow_copy =dict(original_dict)# Modifying the shallow copy
    shallow_copy["age"]=31
    shallow_copy["skills"].append("C#")print("Original dictionary:", original_dict)print("Shallow copy:", shallow_copy)

    Output of the above code is as follows −

    Original dictionary: {'name': 'Bob', 'age': 30, 'skills': ['Java', 'C++', 'C#']}
    Shallow copy: {'name': 'Bob', 'age': 31, 'skills': ['Java', 'C++', 'C#']}
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Deep Copy

    A deep copy creates a new dictionary and recursively copies all objects found in the original dictionary. This means that not only the dictionary itself but also all objects it contains (including nested dictionaries, lists, etc.) are copied. As a result, changes made to the deep copy do not affect the original dictionary and vice versa.

    We can achieve this using the deepcopy() function in the copy module.

    Example

    We can see in the example below that the “age” value in the deep copy is changed, the “skills” list in the deep copy is modified (an item is appended) and the “education” dictionary in the deep copy is modified, all without affecting the original −

    Open Compiler

    import copy
    
    original_dict ={"name":"Alice","age":25,"skills":["Python","Data Science"],"education":{"degree":"Bachelor's","field":"Computer Science"}}# Creating a deep copy
    deep_copy = copy.deepcopy(original_dict)# Modifying the deep copy
    deep_copy["age"]=26
    deep_copy["skills"].append("Machine Learning")
    deep_copy["education"]["degree"]="Master's"# Retrieving both dictionariesprint("Original dictionary:", original_dict)print("Deep copy:", deep_copy)

    This will produce the following output −

    Original dictionary: {'name': 'Alice', 'age': 25, 'skills': ['Python', 'Data Science'], 'education': {'degree': "Bachelor's", 'field': 'Computer Science'}}
    Deep copy: {'name': 'Alice', 'age': 26, 'skills': ['Python', 'Data Science', 'Machine Learning'], 'education': {'degree': "Master's", 'field': 'Computer Science'}}
    

    Copy Dictionaries Using copy() Method

    Dictionaries cannot be copied directly by using the assignment operator (=), you can use the copy() method to create a shallow copy of a dictionary.

    Syntax

    Following is the basic syntax of the copy() method in Python −

    new_dict = original_dict.copy()

    Where, original_dict is the dictionary you want to copy.

    Example

    The following example demonstrates the creation of a shallow copy of a dictionary using the copy() method −

    Open Compiler

    # Creating a dictionary
    dict1 ={"name":"Krishna","age":"27","doy":1992}# Copying the dictionary
    dict2 = dict1.copy()# Printing both of the dictionariesprint("dict1 :", dict1)print("dict2 :", dict2)

    Output

    We will get the output as shown below −

    dict1 : {'name': 'Krishna', 'age': '27', 'doy': 1992}
    dict2 : {'name': 'Krishna', 'age': '27', 'doy': 1992}
  • Loop Dictionaries

    Loop Through Dictionaries

    Looping through dictionaries in Python refers to iterating over key-value pairs within the dictionary and performing operations on each pair. This allows you to access both keys and their corresponding values. There are several ways/methods for looping through dictionaries −

    • Using a for Loop
    • Using dict.items() method
    • Using dict.keys() method
    • Using dict.values() method

    Loop Through Dictionary Using a For Loop

    A for loop in Python is a control flow statement that iterates over a sequence of elements. It repeatedly executes a block of code for each item in the sequence. The sequence can be a range of numbers, a list, a tuple, a string, or any iterable object.

    We can loop through dictionaries using a for loop in Python by iterating over the keys or key-value pairs within the dictionary. There are two common approaches −

    Example: Iterating over Keys

    In this approach, the loop iterates over the keys of the dictionary. Inside the loop, you can access the value corresponding to each key using dictionary indexing −

    Open Compiler

    student ={"name":"Alice","age":21,"major":"Computer Science"}for key in student:print(key, student[key])

    It will produce the following output −

    name Alice
    age 21
    major Computer Science
    

    Example: Iterating over Key-Value Pairs

    In this approach, the loop iterates over the key-value pairs using the items() method of the dictionary. Each iteration provides both the key and its corresponding value −

    Open Compiler

    student ={"name":"Alice","age":21,"major":"Computer Science"}for key, value in student.items():print(key, value)

    We get the output as shown below −

    name Alice
    age 21
    major Computer Science
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Loop Through Dictionary Using dict.items() Method

    The dict.items() method in Python is used to return a view object that displays a list of key-value pairs in the dictionary. This view object provides a dynamic view of the dictionary’s items, allowing you to access both the keys and their corresponding values.

    We can loop through dictionaries using the dict.items() method by iterating over the key-value pairs returned by this method.

    Example

    In this example, the items() method is called on the “student” dictionary, returning a view object containing the key-value pairs. The for loop iterates over each pair, assigning the key to the variable “key” and the corresponding value to the variable “value” −

    Open Compiler

    student ={"name":"Alice","age":21,"major":"Computer Science"}# Looping through key-value pairs for key, value in student.items():print(key, value)

    The output produced is as shown below −

    name Alice
    age 21
    major Computer Science
    

    Loop Through Dictionary Using dict.keys() Method

    The dict.keys() method in Python is used to return a view object that displays a list of keys in the dictionary. This view object provides a dynamic view of the dictionary’s keys, allowing you to access and iterate over them.

    We can loop through dictionaries using the dict.keys() method by iterating over the keys returned by this method. This allows us to access and iterate over the keys of the dictionary.

    Example

    In the example below, the keys() method is called on the “student” dictionary, returning a view object containing the keys. The for loop iterates over each key in the view object, allowing you to perform operations based on the keys of the dictionary during each iteration −

    Open Compiler

    student ={"name":"Alice","age":21,"major":"Computer Science"}# Looping through keys for key in student.keys():print(key)

    Following is the output of the above code −

    name
    age
    major
    

    Loop Through Dictionary Using dict.values() Method

    The dict.values() method in Python is used to return a view object that displays a list of values in the dictionary. This view object provides a dynamic view of the dictionary’s values, allowing you to access and iterate over them.

    We can loop through dictionaries using the dict.values() method by iterating over the values returned by this method. This allows us to access and iterate over the values of the dictionary.

    Example

    In the following example, the values() method is called on the “student” dictionary, returning a view object containing the values −

    Open Compiler

    student ={"name":"Alice","age":21,"major":"Computer Science"}# Looping through values for value in student.values():print(value)

    Output of the above code is as shown below −

    Alice
    21
    Computer Science
  • Dictionary View Objects

    The items()keys(), and values() methods of dict class return view objects. These views are refreshed dynamically whenever any change occurs in the contents of their source dictionary object.

    The items() Method

    The items() method returns a dict_items view object. It contains a list of tuples, each tuple made up of respective key, value pairs.

    Syntax

    Following is the syntax of the items() method −

    Obj =dict.items()

    Return value

    The items() method returns dict_items object which is a dynamic view of (key,value) tuples.

    Example

    In the following example, we first obtain the dict_items object with items() method and check how it is dynamically updated when the dictionary object is updated.

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}
    obj = numbers.items()print('type of obj: ',type(obj))print(obj)print("update numbers dictionary")
    numbers.update({50:"Fifty"})print("View automatically updated")print(obj)

    It will produce the following output −

    type of obj: <class 'dict_items'>
    dict_items([(10, 'Ten'), (20, 'Twenty'), (30, 'Thirty'), (40, 'Forty')])
    update numbers dictionary
    View automatically updated
    dict_items([(10, 'Ten'), (20, 'Twenty'), (30, 'Thirty'), (40, 'Forty'), (50, 'Fifty')])
    

    The keys() Method

    The keys() method of dict class returns dict_keys object which is a list of all keys defined in the dictionary. It is a view object, as it gets automatically updated whenever any update action is done on the dictionary object.

    Syntax

    Following is the syntax of the keys() method −

    Obj =dict.keys()

    Return value

    The keys() method returns dict_keys object which is a view of keys in the dictionary.

    Example

    In this example, we are creating a dictionary named “numbers” with integer keys and their corresponding string values. Then, we obtain a view object “obj” of the keys using the keys() method, and retrieve its type and content −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}
    obj = numbers.keys()print('type of obj: ',type(obj))print(obj)print("update numbers dictionary")
    numbers.update({50:"Fifty"})print("View automatically updated")print(obj)

    It will produce the following output −

    type of obj: <class 'dict_keys'>
    dict_keys([10, 20, 30, 40])
    update numbers dictionary
    View automatically updated
    dict_keys([10, 20, 30, 40, 50])
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    The values() Method

    The values() method returns a view of all the values present in the dictionary. The object is of dict_value type, which gets automatically updated.

    Syntax

    Following is the syntax of the values() method −

    Obj =dict.values()

    Return value

    The values() method returns a dict_values view of all the values present in the dictionary.

    Example

    In the example below, we obtain a view object “obj” of the values using the values() method from the “numbers” dictionary −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}
    obj = numbers.values()print('type of obj: ',type(obj))print(obj)print("update numbers dictionary")
    numbers.update({50:"Fifty"})print("View automatically updated")print(obj)

    It will produce the following output −

    type of obj: <class 'dict_values'>
    dict_values(['Ten', 'Twenty', 'Thirty', 'Forty'])
    update numbers dictionary
    View automatically updated
    dict_values(['Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty'])
  • Remove Dictionary Items

    Remove Dictionary Items

    Removing dictionary items in Python refers to deleting key-value pairs from an existing dictionary. Dictionaries are mutable data structures that hold pairs of keys and their associated values. Each key acts as a unique identifier, mapping to a specific value within the dictionary.

    Removing items from a dictionary allows you to eliminate unnecessary or unwanted data from the dictionary, thereby reducing its size and modifying its content.

    We can remove dictionary items in Python using various ways such as −

    • using the del keyword
    • using the pop() method
    • using the popitem() method
    • using the clear() method
    • using dictionary comprehension

    Remove Dictionary Items Using del Keyword

    The del keyword in Python is used to delete objects. In the context of dictionaries, it is used to remove an item or a slice of items from the dictionary, based on the specified key(s).

    We can remove dictionary items using the del keyword by specifying the key of the item we want to remove. This will delete the key-value pair associated with the specified key from the dictionary.

    Example 1

    In the following example, we are creating a dictionary named numbers with integer keys and their corresponding string values. Then, delete the item with the key ’20’ using the del keyword −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}print("numbers dictionary before delete operation: \n", numbers)del numbers[20]print("numbers dictionary before delete operation: \n", numbers)

    It will produce the following output −

    numbers dictionary before delete operation: 
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
    numbers dictionary before delete operation: 
     {10: 'Ten', 30: 'Thirty', 40: 'Forty'}
    

    Example 2

    The del keyword, when used with a dictionary object, removes the dictionary from memory −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}print("numbers dictionary before delete operation: \n", numbers)del numbers
    print("numbers dictionary before delete operation: \n", numbers)

    Following is the output obtained −

    numbers dictionary before delete operation:
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
    Traceback (most recent call last):
     File "C:\Users\mlath\examples\main.py", line 5, in <module>
      print ("numbers dictionary before delete operation: \n", numbers)
    
                                                           ^^^^^^^
    NameError: name 'numbers' is not defined

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Remove Dictionary Items Using pop() Method

    The pop() method in Python is used to remove a specified key from a dictionary and return the corresponding value. If the specified key is not found, it can optionally return a default value instead of raising a KeyError.

    We can remove dictionary items using the pop() method by specifying the key of the item we want to remove. This method will return the value associated with the specified key and remove the key-value pair from the dictionary.

    Example

    In this example, we are using the pop() method to remove the item with the key ’20’ (storing its value in val) from the ‘numbers’ dictionary. We then retrieve the updated dictionary and the popped value −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}print("numbers dictionary before pop operation: \n", numbers)
    val = numbers.pop(20)print("nubvers dictionary after pop operation: \n", numbers)print("Value popped: ", val)

    Following is the output of the above code −

    numbers dictionary before pop operation: 
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
    nubvers dictionary after pop operation: 
     {10: 'Ten', 30: 'Thirty', 40: 'Forty'}
    Value popped:  Twenty
    

    Remove Dictionary Items Using popitem() Method

    The popitem() method in Python is used to remove and return the last key-value pair from a dictionary.

    Since Python 3.7, dictionaries maintain the insertion order, so popitem() removes the most recently added item. If the dictionary is empty, calling popitem() raises a KeyError.

    We can remove dictionary items using the popitem() method by calling the method on the dictionary, which removes and returns the last key-value pair added to the dictionary.

    Example

    In the example below, we use the popitem() method to remove an arbitrary item from the dictionary ‘numbers’ (storing both its key-value pair in val), and retrieve the updated dictionary along with the popped key-value pair −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}print("numbers dictionary before pop operation: \n", numbers)
    val = numbers.popitem()print("numbers dictionary after pop operation: \n", numbers)print("Value popped: ", val)

    Output of the above code is as shown below −

    numbers dictionary before pop operation: 
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
    numbers dictionary after pop operation: 
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty'}
    Value popped:  (40, 'Forty')
    

    Remove Dictionary Items Using clear() Method

    The clear() method in Python is used to remove all items from a dictionary. It effectively empties the dictionary, leaving it with a length of 0.

    We can remove dictionary items using the clear() method by calling it on the dictionary object. This method removes all key-value pairs from the dictionary, effectively making it empty.

    Example

    In the following example, we are using the clear() method to remove all items from the dictionary ‘numbers’ −

    Open Compiler

    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}print("numbers dictionary before clear method: \n", numbers)
    numbers.clear()print("numbers dictionary after clear method: \n", numbers)

    We get the output as shown below −

    numbers dictionary before clear method: 
     {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
    numbers dictionary after clear method: 
     {}
    

    Remove Dictionary Items Using Dictionary Comprehension

    Dictionary comprehension is a concise way to create dictionaries in Python. It follows the same syntax as list comprehension but generates dictionaries instead of lists. With dictionary comprehension, you can iterate over iterable objects (such as lists, tuples, or other dictionaries), apply an expression to each item, and construct key-value pairs based on the result of that expression.

    We cannot directly remove dictionary items using dictionary comprehension. Dictionary comprehension is primarily used for creating new dictionaries based on some transformation or filtering of existing data, rather than for removing items from dictionaries.

    If you need to remove items from a dictionary based on certain conditions, you would typically use other methods like del, pop(), or popitem(). These methods allow you to explicitly specify which items to remove from the dictionary.

    Example

    In this example, we remove items ‘age’ and ‘major’ from the ‘student_info’ dictionary based on a predefined list of keys to remove −

    Open Compiler

    # Creating a dictionary
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Removing items based on conditions
    keys_to_remove =["age","major"]for key in keys_to_remove:
    
    student_info.pop(key,None)print(student_info)</code></pre>

    The output obtained is as shown below −

    {'name': 'Alice'}
  • Event Management System

    You can install Flask using pip if you haven’t already:

    pip install Flask
    

    Project Structure

    event_management_system/
    
    ├── app.py
    ├── templates/
    │   ├── index.html
    │   ├── create_event.html
    │   └── event_details.html
    └── static/
        └── style.css

    Step 1: Setting Up Flask

    app.py

    This will be the main application file.

    from flask import Flask, render_template, request, redirect, url_for
    import sqlite3
    
    app = Flask(__name__)
    
    # Database setup
    def init_db():
    
    with sqlite3.connect("events.db") as conn:
        cursor = conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS events (
                id INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                description TEXT NOT NULL,
                date TEXT NOT NULL,
                location TEXT NOT NULL
            )
        ''')
        conn.commit()
    @app.route('/') def index():
    conn = sqlite3.connect("events.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM events")
    events = cursor.fetchall()
    conn.close()
    return render_template('index.html', events=events)
    @app.route('/event/<int:event_id>') def event_details(event_id):
    conn = sqlite3.connect("events.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM events WHERE id = ?", (event_id,))
    event = cursor.fetchone()
    conn.close()
    return render_template('event_details.html', event=event)
    @app.route('/create_event', methods=['GET', 'POST']) def create_event():
    if request.method == 'POST':
        name = request.form&#91;'name']
        description = request.form&#91;'description']
        date = request.form&#91;'date']
        location = request.form&#91;'location']
        
        conn = sqlite3.connect("events.db")
        cursor = conn.cursor()
        cursor.execute("INSERT INTO events (name, description, date, location) VALUES (?, ?, ?, ?)",
                       (name, description, date, location))
        conn.commit()
        conn.close()
        
        return redirect(url_for('index'))
    
    return render_template('create_event.html')
    if __name__ == '__main__':
    init_db()
    app.run(debug=True)

    Step 2: Creating HTML Templates

    templates/index.html

    This will display all events.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    &lt;title>Event Management System&lt;/title>
    </head> <body>
    &lt;h1>Events&lt;/h1>
    &lt;a href="{{ url_for('create_event') }}">Create New Event&lt;/a>
    &lt;ul>
        {% for event in events %}
            &lt;li>
                &lt;a href="{{ url_for('event_details', event_id=event&#91;0]) }}">{{ event&#91;1] }}&lt;/a> - {{ event&#91;3] }} @ {{ event&#91;4] }}
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    templates/create_event.html

    This allows users to create new events.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    &lt;title>Create Event&lt;/title>
    </head> <body>
    &lt;h1>Create New Event&lt;/h1>
    &lt;form method="POST">
        &lt;label>Name: &lt;input type="text" name="name" required>&lt;/label>&lt;br>
        &lt;label>Description: &lt;textarea name="description" required>&lt;/textarea>&lt;/label>&lt;br>
        &lt;label>Date: &lt;input type="date" name="date" required>&lt;/label>&lt;br>
        &lt;label>Location: &lt;input type="text" name="location" required>&lt;/label>&lt;br>
        &lt;button type="submit">Create Event&lt;/button>
    &lt;/form>
    &lt;a href="{{ url_for('index') }}">Back to Events&lt;/a>
    </body> </html>

    templates/event_details.html

    This shows the details of a single event.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    &lt;title>{{ event&#91;1] }}&lt;/title>
    </head> <body>
    &lt;h1>{{ event&#91;1] }}&lt;/h1>
    &lt;p>{{ event&#91;2] }}&lt;/p>
    &lt;p>Date: {{ event&#91;3] }}&lt;/p>
    &lt;p>Location: {{ event&#91;4] }}&lt;/p>
    &lt;a href="{{ url_for('index') }}">Back to Events&lt;/a>
    </body> </html>

    Step 3: Add Some Styles

    static/style.css

    Add some basic styling.

    body {
    
    font-family: Arial, sans-serif;
    } h1 {
    color: #333;
    } ul {
    list-style-type: none;
    } li {
    margin: 10px 0;
    }

    Step 4: Run the Application

    Now you can run your application:

    bashCopy codepython app.py
    

    Visit http://127.0.0.1:5000 in your web browser, and you should see the Event Management System in action!

    Additional Features

    This is a basic example. You might want to extend this system with features like:

    • User authentication
    • Event registration
    • Notification system
    • Advanced search functionality

  • Add Dictionary Items

    Add Dictionary Items

    Adding dictionary items in Python refers to inserting new key-value pairs into an existing dictionary. Dictionaries are mutable data structures that store collections of key-value pairs, where each key is associated with a corresponding value.

    Adding items to a dictionary allows you to dynamically update and expand its contents as needed during program execution.

    We can add dictionary items in Python using various ways such as −

    • Using square brackets
    • Using the update() method
    • Using a comprehension
    • Using unpacking
    • Using the Union Operator
    • Using the |= Operator
    • Using setdefault() method
    • Using collections.defaultdict() method

    Add Dictionary Item Using Square Brackets

    The square brackets [] in Python is used to access elements in sequences like lists and strings through indexing and slicing operations. Additionally, when working with dictionaries, square brackets are used to specify keys for accessing or modifying associated values.

    You can add items to a dictionary by specifying the key within square brackets and assigning a value to it. If the key is already present in the dictionary object, its value will be updated to val. If the key is not present in the dictionary, a new key-value pair will be added.

    Example

    In this example, we are creating a dictionary named “marks” with keys representing names and their corresponding integer values. Then, we add a new key-value pair ‘Kavta’: 58 to the dictionary using square bracket notation −

    Open Compiler

    marks ={"Savita":67,"Imtiaz":88,"Laxman":91,"David":49}print("Initial dictionary: ", marks)
    marks['Kavya']=58print("Dictionary after new addition: ", marks)

    It will produce the following output −

    Initial dictionary:  {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
    Dictionary after new addition:  {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49, 'Kavya': 58}
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Add Dictionary Item Using the update() Method

    The update() method in Python dictionaries is used to merge the contents of another dictionary or an iterable of key-value pairs into the current dictionary. It adds or updates key-value pairs, ensuring that existing keys are updated with new values and new keys are added to the dictionary.

    You can add multiple items to a dictionary using the update() method by passing another dictionary or an iterable of key-value pairs.

    Example

    In the following example, we use the update() method to add multiple new key-value pairs ‘Kavya’: 58 and ‘Mohan’: 98 to the dictionary ‘marks’ −

    Open Compiler

    marks ={"Savita":67,"Imtiaz":88}print("Initial dictionary: ", marks)
    marks.update({'Kavya':58,'Mohan':98})print("Dictionary after new addition: ", marks)

    We get the output as shown below −

    Initial dictionary:  {'Savita': 67, 'Imtiaz': 88}
    Dictionary after new addition:  {'Savita': 67, 'Imtiaz': 88, 'Kavya': 58, 'Mohan': 98}
    

    Add Dictionary Item Using Unpacking

    Unpacking in Python refers to extracting individual elements from a collection, such as a list, tuple, or dictionary, and assigning them to variables in a single statement. This can be done using the * operator for iterables like lists and tuples, and the ** operator for dictionaries.

    We can add dictionary items using unpacking by combining two or more dictionaries with the ** unpacking operator.

    Example

    In the example below, we are initializing two dictionaries named “marks” and “marks1”, both containing names and their corresponding integer values. Then, we create a new dictionary “newmarks” by merging “marks” and “marks1” using dictionary unpacking −

    Open Compiler

    marks ={"Savita":67,"Imtiaz":88,"Laxman":91,"David":49}print("marks dictionary before update: \n", marks)
    marks1 ={"Sharad":51,"Mushtaq":61,"Laxman":89}
    newmarks ={**marks,**marks1}print("marks dictionary after update: \n", newmarks)

    Following is the output of the above code −

    marks dictionary before update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
    marks dictionary after update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
    

    Add Dictionary Item Using the Union Operator (|)

    The union operator in Python, represented by the | symbol, is used to combine the elements of two sets into a new set that contains all the unique elements from both sets. It can also be used with dictionaries in Python 3.9 and later to merge the contents of two dictionaries.

    We can add dictionary items using the union operator by merging two dictionaries into a new dictionary, which includes all key-value pairs from both dictionaries.

    Example

    In this example, we are using the | operator to combine the dictionaries “marks” and “marks1” with “marks1” values taking precedence in case of duplicate keys −

    Open Compiler

    marks ={"Savita":67,"Imtiaz":88,"Laxman":91,"David":49}print("marks dictionary before update: \n", marks)
    marks1 ={"Sharad":51,"Mushtaq":61,"Laxman":89}
    newmarks = marks | marks1
    print("marks dictionary after update: \n", newmarks)

    Output of the above code is as shown below −

    marks dictionary before update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
    marks dictionary after update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
    

    Add Dictionary Item Using the “|=” Operator

    The |= operator in Python is an in-place union operator for sets and dictionaries. It updates the set or dictionary on the left-hand side with elements from the set or dictionary on the right-hand side.

    We can add dictionary items using the |= operator by updating an existing dictionary with key-value pairs from another dictionary. If there are overlapping keys, the values from the right-hand dictionary will overwrite those in the left-hand dictionary.

    Example

    In the following example, we use the |= operator to update “marks” with the key-value pairs from “marks1”, with values from “marks1” taking precedence in case of duplicate keys −

    Open Compiler

    marks ={"Savita":67,"Imtiaz":88,"Laxman":91,"David":49}print("marks dictionary before update: \n", marks)
    marks1 ={"Sharad":51,"Mushtaq":61,"Laxman":89}
    marks |= marks1
    print("marks dictionary after update: \n", marks)

    The output produced is as shown below −

    marks dictionary before update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
    marks dictionary after update:
     {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
    

    Add Dictionary Item Using the setdefault() Method

    The setdefault() method in Python is used to get the value of a specified key in a dictionary. If the key does not exist, it inserts the key with a specified default value.

    We can add dictionary items using the setdefault() method by specifying a key and a default value.

    Example

    In this example, we use the setdefault() to add the key-value pair “major”: “Computer Science” to the “student” dictionary −

    Open Compiler

    # Initial dictionary
    student ={"name":"Alice","age":21}# Adding a new key-value pair
    major = student.setdefault("major","Computer Science")print(student)

    Since the key “major” does not exist, it is added with the specified default value as shown in the output below −

    {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
    

    Add Dictionary Item Using the collections.defaultdict() Method

    The collections.defaultdict() method in Python is a subclass of the built-in “dict” class that creates dictionaries with default values for keys that have not been set yet. It is part of the collections module in Python’s standard library.

    We can add dictionary items using the collections.defaultdict() method by specifying a default factory, which determines the default value for keys that have not been set yet. When accessing a missing key for the first time, the default factory is called to create a default value, and this value is inserted into the dictionary.

    Example

    In this example, we are initializing instances of defaultdict with different default factories: int to initialize missing keys with 0, list to initialize missing keys with an empty list, and a custom function default_value to initialize missing keys with the return value of the function −

    Open Compiler

    from collections import defaultdict
    # Using int as the default factory to initialize missing keys with 0
    d = defaultdict(int)# Incrementing the value for key 'a'
    d["a"]+=1print(d)# Using list as the default factory to initialize missing keys with an empty list
    d = defaultdict(list)# Appending to the list for key 'b'
    d["b"].append(1)print(d)# Using a custom function as the default factorydefdefault_value():return"N/A"
    
    d = defaultdict(default_value)print(d["c"])

    The output obtained is as follows −

    defaultdict(<class 'int'>, {'a': 1})
    defaultdict(<class 'list'>, {'b': [1]})
    N/A
  • Real Estate Listing Website

    Project Structure

    real-estate-website/
    ├── server.js
    ├── package.json
    ├── public/
    │   ├── index.html
    │   ├── style.css
    │   └── script.js
    └── data/
    
    └── listings.json

    Step 1: Setup Node.js Server

    1. Initialize Node.js Project:
    mkdir real-estate-website cd real-estate-website npm init -y npm install express
    1. Create server.js:
    // server.js const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = process.env.PORT || 3000; app.use(express.static('public')); app.use(express.json()); // Endpoint to get listings app.get('/api/listings', (req, res) => { fs.readFile(path.join(__dirname, 'data', 'listings.json'), 'utf8', (err, data) => { if (err) { res.status(500).send('Error reading listings'); } else { res.json(JSON.parse(data)); } }); }); app.listen(PORT, () => { console.log(Server is running on http://localhost:${PORT}); });

    Step 2: Create Frontend

    1. Create index.html in public/:
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real Estate Listings</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Real Estate Listings</h1> <div id="listings"></div> <script src="script.js"></script> </body> </html>
    1. Create style.css in public/:
    body { font-family: Arial, sans-serif; margin: 20px; } h1 { text-align: center; } #listings { display: flex; flex-wrap: wrap; justify-content: center; } .listing { border: 1px solid #ccc; margin: 10px; padding: 10px; width: 300px; }
    1. Create script.js in public/:
    // script.js fetch('/api/listings') .then(response => response.json()) .then(data => { const listingsDiv = document.getElementById('listings'); data.forEach(listing => { const listingDiv = document.createElement('div'); listingDiv.className = 'listing'; listingDiv.innerHTML =  &lt;h2>${listing.title}&lt;/h2> &lt;p>${listing.description}&lt;/p> &lt;p>Price: $${listing.price}&lt;/p> ; listingsDiv.appendChild(listingDiv); }); }) .catch(error => console.error('Error fetching listings:', error));

    Step 3: Create Listings Data

    1. Create listings.json in data/:
    [ { "title": "Beautiful Family Home", "description": "A spacious home with a beautiful garden.", "price": 350000 }, { "title": "Modern Apartment", "description": "A stylish apartment in the city center.", "price": 250000 }, { "title": "Cozy Cottage", "description": "A charming cottage in a quiet neighborhood.", "price": 180000 } ]

    Step 4: Run the Application

    1. Start the Server:bashCopy codenode server.js
    2. Access the Application:Open your browser and go to http://localhost:3000.