Author: saqibkhan

  • Change Dictionary Items

    Change Dictionary Items

    Changing dictionary items in Python refers to modifying the values associated with specific keys within a dictionary. This can involve updating the value of an existing key, adding a new key-value pair, or removing a key-value pair from the dictionary.

    Dictionaries are mutable, meaning their contents can be modified after they are created.

    Modifying Dictionary Values

    Modifying values in a Python dictionary refers to changing the value associated with an existing key. To achieve this, you can directly assign a new value to that key.

    Example

    In the following example, we are defining a dictionary named “person” with keys ‘name’, ‘age’, and ‘city’ and their corresponding values. Then, we modify the value associated with the key ‘age’ to 26 −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Modifying the value associated with the key 'age'
    person['age']=26print(person)

    It will produce the following output −

    {'name': 'Alice', 'age': 26, 'city': 'New York'}
    

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

    Updating Multiple Dictionary Values

    If you need to update multiple values in a dictionary at once, you can use the update() method. This method is used to update a dictionary with elements from another dictionary or an iterable of key-value pairs.

    The update() method adds the key-value pairs from the provided dictionary or iterable to the original dictionary, overwriting any existing keys with the new values if they already exist in the original dictionary.

    Example

    In the example below, we are using the update() method to modify the values associated with the keys ‘age’ and ‘city’ in the ‘persons’ dictionary −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Updating multiple values
    person.update({'age':26,'city':'Los Angeles'})print(person)

    We get the output as shown below −

    {'name': 'Alice', 'age': 26, 'city': 'Los Angeles'}
    

    Conditional Dictionary Modification

    Conditional modification in a Python dictionary refers to changing the value associated with a key only if a certain condition is met.

    You can use an if statement to check whether a certain condition is true before modifying the value associated with a key.

    Example

    In this example, we conditionally modify the value associated with the key ‘age’ to ’26’ if the current value is ’25’ in the ‘persons’ dictionary −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Conditionally modifying the value associated with 'age'if person['age']==25:
       person['age']=26print(person)

    The output obtained is as shown below −

    {'name': 'Alice', 'age': 26, 'city': 'New York'}
    

    Modify Dictionary by Adding New Key-Value Pairs

    Adding new key-value pairs to a Python dictionary refers to inserting a new key along with its corresponding value into the dictionary.

    This process allows you to dynamically expand the data stored in the dictionary by including additional information as needed.

    Example: Using Assignment Operator

    You can add a new key-value pair to a dictionary by directly assigning a value to a new key as shown below. In the example below, the key ‘city’ with the value ‘New York’ is added to the ‘person’ dictionary −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25}# Adding a new key-value pair 'city': 'New York'
    person['city']='New York'print(person)

    The result produced is as follows −

    {'name': 'Alice', 'age': 25, 'city': 'New York'}
    

    Example: Using the setdefault() Method

    You can use the setdefault() method to add a new key-value pair to a dictionary if the key does not already exist.

    In this example, the setdefault() method adds the new key ‘city’ with the value ‘New York’ to the ‘person’ dictionary only if the key ‘city’ does not already exist −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25}# Adding a new key-value pair 'city': 'New York'
    person.setdefault('city','New York')print(person)

    Following is the output of the above code −

    {'name': 'Alice', 'age': 25, 'city': 'New York'}
    

    Modify Dictionary by Removing Key-Value Pairs

    Removing key-value pairs from a Python dictionary refers to deleting specific keys along with their corresponding values from the dictionary.

    This process allows you to selectively remove data from the dictionary based on the keys you want to eliminate.

    Example: Using the del Statement

    You can use the del statement to remove a specific key-value pair from a dictionary. In this example, the del statement removes the key ‘age’ along with its associated value from the ‘person’ dictionary −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Removing the key-value pair associated with the key 'age'del person['age']print(person)

    Output of the above code is as shown below −

    {'name': 'Alice', 'city': 'New York'}
    

    Example: Using the pop() Method

    You can also use the pop() method to remove a specific key-value pair from a dictionary and return the value associated with the removed key.

    In here, the pop() method removes the key ‘age’ along with its associated value from the ‘person’ dictionary −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Removing the key-value pair associated with the key 'age'
    removed_age = person.pop('age')print(person)print("Removed age:", removed_age)

    It will produce the following output −

    {'name': 'Alice', 'city': 'New York'}
    Removed age: 25
    

    Example: Using the popitem() Method

    You can use the popitem() method as well to remove the last key-value pair from a dictionary and return it as a tuple.

    Now, the popitem() method removes the last key-value pair from the ‘person’ dictionary and returns it as a tuple −

    Open Compiler

    # Initial dictionary
    person ={'name':'Alice','age':25,'city':'New York'}# Removing the last key-value pair 
    removed_item = person.popitem()print(person)print("Removed item:", removed_item)

    We get the output as shown below −

    {'name': 'Alice', 'age': 25}
    Removed item: ('city', 'New York')
  • Online Learning Portal

    Directory Structure

    online_learning_portal/
    │
    ├── app.py
    ├── templates/
    │   ├── base.html
    │   ├── index.html
    │   └── course.html
    └── static/
    
    └── style.css

    1. Setting Up the Flask App

    app.py

    from flask import Flask, render_template, url_for, redirect
    
    app = Flask(__name__)
    
    # Sample data for courses
    courses = [
    
    {'id': 1, 'title': 'Python for Beginners', 'description': 'Learn Python from scratch!'},
    {'id': 2, 'title': 'Web Development with Flask', 'description': 'Build web applications using Flask.'},
    ] @app.route('/') def index():
    return render_template('index.html', courses=courses)
    @app.route('/course/<int:course_id>') def course(course_id):
    course = next((c for c in courses if c&#91;'id'] == course_id), None)
    return render_template('course.html', course=course)
    if __name__ == '__main__':
    app.run(debug=True)

    2. Creating the HTML Templates

    templates/base.html

    <!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>Online Learning Portal&lt;/title>
    </head> <body>
    &lt;header>
        &lt;h1>Online Learning Portal&lt;/h1>
        &lt;nav>
            &lt;a href="{{ url_for('index') }}">Home&lt;/a>
        &lt;/nav>
    &lt;/header>
    &lt;main>
        {% block content %}{% endblock %}
    &lt;/main>
    &lt;footer>
        &lt;p>&amp;copy; 2024 Online Learning Portal&lt;/p>
    &lt;/footer>
    </body> </html>

    templates/index.html

    {% extends 'base.html' %}
    
    {% block content %}
    <h2>Available Courses</h2>
    <ul>
    
    {% for course in courses %}
        &lt;li>
            &lt;a href="{{ url_for('course', course_id=course.id) }}">{{ course.title }}&lt;/a> - {{ course.description }}
        &lt;/li>
    {% endfor %}
    </ul> {% endblock %}

    templates/course.html

    htmlCopy code{% extends 'base.html' %}
    
    {% block content %}
    <h2>{{ course.title }}</h2>
    <p>{{ course.description }}</p>
    <a href="{{ url_for('index') }}">Back to Courses</a>
    {% endblock %}
    

    3. Adding Some Basic Styles

    static/style.css

    body {
    
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    } header {
    background: #007BFF;
    color: white;
    padding: 1rem;
    } nav a {
    color: white;
    margin: 0 1rem;
    text-decoration: none;
    } ul {
    list-style: none;
    padding: 0;
    } footer {
    text-align: center;
    padding: 1rem;
    background: #f1f1f1;
    position: relative;
    bottom: 0;
    width: 100%;
    }

    4. Running the App

    1. Navigate to the project directory.
    2. Run the app using the command:bashCopy codepython app.py
    3. Open your web browser and go to http://127.0.0.1:5000/.

    Future Enhancements

    • User authentication (login/signup).
    • Course content management (videos, quizzes).
    • Database integration (like SQLite or PostgreSQL) for persistent data storage.
    • A more complex frontend (using frameworks like React or Vue.js).
  • Access Dictionary Items

    Access Dictionary Items

    Accessing dictionary items in Python involves retrieving the values associated with specific keys within a dictionary data structure. Dictionaries are composed of key-value pairs, where each key is unique and maps to a corresponding value. Accessing dictionary items allows you to retrieve these values by providing the respective keys.

    There are various ways to access dictionary items in Python. They include −

    • Using square brackets []
    • The get() method
    • Iterating through the dictionary using loops
    • Or specific methods like keys(), values(), and items()

    We will discuss each method in detail to understand how to access and retrieve data from dictionaries.

    Access Dictionary Items Using Square Brackets []

    In Python, the square brackets [] are used for creating lists, accessing elements from a list or other iterable objects (like strings, tuples, or dictionaries), and for list comprehension.

    We can access dictionary items using square brackets by providing the key inside the brackets. This retrieves the value associated with the specified key.

    Example 1

    In the following example, we are defining a dictionary named “capitals” where each key represents a state and its corresponding value represents the capital city.

    Then, we access and retrieve the capital cities of Gujarat and Karnataka using their respective keys ‘Gujarat’ and ‘Karnataka’ from the dictionary −

    Open Compiler

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}print("Capital of Gujarat is : ", capitals['Gujarat'])print("Capital of Karnataka is : ", capitals['Karnataka'])

    It will produce the following output −

    Capital of Gujarat is: Gandhinagar
    Capital of Karnataka is: Bengaluru
    

    Example 2

    Python raises a KeyError if the key given inside the square brackets is not present in the dictionary object −

    Open Compiler

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}print("Captial of Haryana is : ", capitals['Haryana'])

    Following is the error obtained −

       print ("Captial of Haryana is : ", capitals['Haryana'])
    
                                      ~~~~~~~~^^^^^^^^^^^
    KeyError: 'Haryana'

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

    Access Dictionary Items Using get() Method

    The get() method in Python’s dict class is used to retrieve the value associated with a specified key. If the key is not found in the dictionary, it returns a default value (usually None) instead of raising a KeyError.

    We can access dictionary items using the get() method by specifying the key as an argument. If the key exists in the dictionary, the method returns the associated value; otherwise, it returns a default value, which is often None unless specified otherwise.

    Syntax

    Following is the syntax of the get() method in Python −

    Val =dict.get("key")

    where, key is an immutable object used as key in the dictionary object.

    Example 1

    In the example below, we are defining a dictionary named “capitals” where each key-value pair maps a state to its capital city. Then, we use the get() method to retrieve the capital cities of “Gujarat” and “Karnataka” −

    Open Compiler

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}print("Capital of Gujarat is: ", capitals.get('Gujarat'))print("Capital of Karnataka is: ", capitals.get('Karnataka'))

    We get the output as shown below −

    Capital of Gujarat is: Gandhinagar
    Capital of Karnataka is: Bengaluru
    

    Example 2

    Unlike the “[]” operator, the get() method doesn’t raise error if the key is not found; it return None −

    Open Compiler

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}print("Capital of Haryana is : ", capitals.get('Haryana'))

    It will produce the following output −

    Capital of Haryana is : None
    

    Example 3

    The get() method accepts an optional string argument. If it is given, and if the key is not found, this string becomes the return value −

    Open Compiler

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}print("Capital of Haryana is : ", capitals.get('Haryana','Not found'))

    After executing the above code, we get the following output −

    Capital of Haryana is: Not found
    

    Access Dictionary Keys

    In a dictionary, keys are the unique identifiers associated with each value. They act as labels or indices that allow you to access and retrieve the corresponding value. Keys are immutable, meaning they cannot be changed once they are assigned. They must be of an immutable data type, such as strings, numbers, or tuples.

    We can access dictionary keys in Python using the keys() method, which returns a view object containing all the keys in the dictionary.

    Example

    In this example, we are retrieving all the keys from the dictionary “student_info” using the keys() method −

    Open Compiler

    # Creating a dictionary with keys and values
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Accessing all keys using the keys() method
    all_keys = student_info.keys()print("Keys:", all_keys)

    Following is the output of the above code −

    Keys: dict_keys(['name', 'age', 'major'])
    

    Access Dictionary Values

    In a dictionary, values are the data associated with each unique key. They represent the actual information stored in the dictionary and can be of any data type, such as strings, integers, lists, other dictionaries, and more. Each key in a dictionary maps to a specific value, forming a key-value pair.

    We can access dictionary values in Python using −

    • Square Brackets ([]) − By providing the key inside the brackets.
    • The get() Method − By calling the method with the key as an argument, optionally providing a default value.
    • The values() Method − which returns a view object containing all the values in the dictionary

    Example 1

    In this example, we are directly accessing associated with the key “name” and “age” using the sqaure brackets −

    Open Compiler

    # Creating a dictionary with student information
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Accessing dictionary values using square brackets
    name = student_info["name"]
    age = student_info["age"]print("Name:", name)print("Age:", age)

    Output of the above code is as follows −

    Name: Alice
    Age: 21
    

    Example 2

    In here, we use the get() method to retrieve the value associated with the key “major” and provide a default value of “2023” for the key “graduation_year” −

    Open Compiler

    # Creating a dictionary with student information
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Accessing dictionary values using the get() method
    major = student_info.get("major")# Default value provided if key is not found
    grad_year = student_info.get("graduation_year","2023")print("Major:", major)print("Graduation Year:", grad_year)

    We get the result as follows −

    Major: Computer Science
    Graduation Year: 2023
    

    Example 3

    Now, we are retrieving all the values from the dictionary “student_info” using the values() method −

    Open Compiler

    # Creating a dictionary with keys and values
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Accessing all values using the values() method
    all_values = student_info.values()print("Values:", all_values)

    The result obtained is as shown below −

    Values: dict_values(['Alice', 21, 'Computer Science'])
    

    Access Dictionary Items Using the items() Function

    The items() function in Python is used to return a view object that displays a list of a dictionary’s key-value tuple pairs.

    This view object can be used to iterate over the dictionary’s keys and values simultaneously, making it easy to access both the keys and the values in a single loop.

    Example

    In the following example, we are using the items() function to retrieve all the key-value pairs from the dictionary “student_info” −

    Open Compiler

    # Creating a dictionary with student information
    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Using the items() method to get key-value pairs
    all_items = student_info.items()print("Items:", all_items)# Iterating through the key-value pairsprint("Iterating through key-value pairs:")for key, value in all_items:print(f"{key}: {value}")

    Following is the output of the above code −

    Items: dict_items([('name', 'Alice'), ('age', 21), ('major', 'Computer Science')])
    Iterating through key-value pairs:
    name: Alice
    age: 21
    major: Computer Science
  • Social Media Dashboard

    Step 1: Basic Structure (HTML)

    Create an index.html file with the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Social Media Dashboard&lt;/title>
    &lt;link rel="stylesheet" href="styles.css">
    </head> <body>
    &lt;div class="dashboard">
        &lt;h1>Social Media Dashboard&lt;/h1>
        &lt;div class="cards">
            &lt;div class="card" id="followers-card">
                &lt;h2>Followers&lt;/h2>
                &lt;p id="followers-count">0&lt;/p>
            &lt;/div>
            &lt;div class="card" id="likes-card">
                &lt;h2>Likes&lt;/h2>
                &lt;p id="likes-count">0&lt;/p>
            &lt;/div>
            &lt;div class="card" id="posts-card">
                &lt;h2>Posts&lt;/h2>
                &lt;p id="posts-count">0&lt;/p>
            &lt;/div>
        &lt;/div>
        &lt;button id="update-data">Update Data&lt;/button>
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    Step 2: Basic Styling (CSS)

    Create a styles.css file for the dashboard styling:

    body {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .dashboard {
    max-width: 800px;
    margin: auto;
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } .cards {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    } .card {
    flex: 1;
    margin: 0 10px;
    padding: 20px;
    background: #e7e7e7;
    border-radius: 10px;
    text-align: center;
    } button {
    display: block;
    margin: 20px auto;
    padding: 10px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    } button:hover {
    background: #0056b3;
    }

    Step 3: Adding Functionality (JavaScript)

    Create a script.js file to handle updating the dashboard:

    const followersCount = document.getElementById('followers-count');
    const likesCount = document.getElementById('likes-count');
    const postsCount = document.getElementById('posts-count');
    
    document.getElementById('update-data').addEventListener('click', updateData);
    
    function updateData() {
    
    // Simulated random data for demonstration
    followersCount.textContent = Math.floor(Math.random() * 1000);
    likesCount.textContent = Math.floor(Math.random() * 500);
    postsCount.textContent = Math.floor(Math.random() * 200);
    }

    Explanation

    1. HTML Structure: The HTML creates a basic layout with sections for followers, likes, and posts.
    2. CSS Styling: The CSS styles the dashboard, making it visually appealing with responsive design.
    3. JavaScript Functionality: The JavaScript code simulates updating the data when the button is clicked. In a real application, you’d replace this with API calls to fetch real data.
  • Task Management Tool

    Task Management Tool

    HTML (index.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Task Management Tool&lt;/title>
    &lt;link rel="stylesheet" href="styles.css">
    </head> <body>
    &lt;div class="container">
        &lt;h1>Task Manager&lt;/h1>
        &lt;input type="text" id="taskInput" placeholder="Add a new task...">
        &lt;button id="addTaskButton">Add Task&lt;/button>
        &lt;ul id="taskList">&lt;/ul>
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    CSS (styles.css)

    body {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
    } .container {
    max-width: 600px;
    margin: auto;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } input[type="text"] {
    width: 70%;
    padding: 10px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    } button {
    padding: 10px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    } button:hover {
    background-color: #218838;
    } ul {
    list-style: none;
    padding: 0;
    } li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #ddd;
    } li.completed {
    text-decoration: line-through;
    color: #aaa;
    } .delete-button {
    background: none;
    border: none;
    color: #dc3545;
    cursor: pointer;
    }

    JavaScript (script.js)

    document.getElementById('addTaskButton').addEventListener('click', addTask);
    document.getElementById('taskInput').addEventListener('keypress', function(e) {
    
    if (e.key === 'Enter') {
        addTask();
    }
    }); function addTask() {
    const taskInput = document.getElementById('taskInput');
    const taskText = taskInput.value.trim();
    
    if (taskText === '') {
        alert('Please enter a task');
        return;
    }
    const li = document.createElement('li');
    li.textContent = taskText;
    const completeButton = document.createElement('button');
    completeButton.textContent = '✓';
    completeButton.onclick = () => {
        li.classList.toggle('completed');
    };
    
    const deleteButton = document.createElement('button');
    deleteButton.textContent = '✖';
    deleteButton.classList.add('delete-button');
    deleteButton.onclick = () => {
        li.remove();
    };
    li.appendChild(completeButton);
    li.appendChild(deleteButton);
    document.getElementById('taskList').appendChild(li);
    
    taskInput.value = '';
    }

    How to Run

    1. Create a Project Directory: Create a folder for your project, e.g., task-manager.
    2. Create Files: Inside this folder, create three files: index.html, styles.css, and script.js.
    3. Copy the Code: Copy the HTML, CSS, and JavaScript code provided above into their respective files.
    4. Open in a Browser: Open index.html in your web browser to see the task management tool in action.

  • Dictionaries

    Dictionaries in Python

    In Python, a dictionary is a built-in data type that stores data in key-value pairs. It is an unordered, mutable, and indexed collection. Each key in a dictionary is unique and maps to a value. Dictionaries are often used to store data that is related, such as information associated with a specific entity or object, where you can quickly retrieve a value based on its key.

    Python’s dictionary is an example of a mapping type. A mapping object ‘maps’ the value of one object to another. To establish mapping between a key and a value, the colon (:) symbol is put between the two.

    Each key-value pair is separated by a comma and enclosed within curly braces {}. The key and value within each pair are separated by a colon (:), forming the structure key:value.

    Given below are some examples of Python dictionary objects −

    capitals ={"Maharashtra":"Mumbai","Gujarat":"Gandhinagar","Telangana":"Hyderabad","Karnataka":"Bengaluru"}
    numbers ={10:"Ten",20:"Twenty",30:"Thirty",40:"Forty"}
    marks ={"Savita":67,"Imtiaz":88,"Laxman":91,"David":49}

    Key Features of Dictionaries

    Following are the key features of dictionaries −

    • Unordered − The elements in a dictionary do not have a specific order. Python dictionaries before version 3.7 did not maintain insertion order. Starting from Python 3.7, dictionaries maintain insertion order as a language feature.
    • Mutable − You can change, add, or remove items after the dictionary has been created.
    • Indexed − Although dictionaries do not have numeric indexes, they use keys as indexes to access the associated values.
    • Unique Keys − Each key in a dictionary must be unique. If you try to assign a value to an existing key, the old value will be replaced by the new value.
    • Heterogeneous − Keys and values in a dictionary can be of any data type.

    Example 1

    Only a number, string or tuple can be used as key. All of them are immutable. You can use an object of any type as the value. Hence following definitions of dictionary are also valid −

    Open Compiler

    d1 ={"Fruit":["Mango","Banana"],"Flower":["Rose","Lotus"]}
    d2 ={('India, USA'):'Countries',('New Delhi','New York'):'Capitals'}print(d1)print(d2)

    It will produce the following output −

    {'Fruit': ['Mango', 'Banana'], 'Flower': ['Rose', 'Lotus']}
    {'India, USA': 'Countries', ('New Delhi', 'New York'): 'Capitals'}
    

    Example 2

    Python doesn’t accept mutable objects such as list as key, and raises TypeError.

    Open Compiler

    d1 ={["Mango","Banana"]:"Fruit","Flower":["Rose","Lotus"]}print(d1)

    It will raise a TypeError −

    Traceback (most recent call last):
       File "C:\Users\Sairam\PycharmProjects\pythonProject\main.py", line 8, in <module>
    d1 = {["Mango","Banana"]:"Fruit", "Flower":["Rose", "Lotus"]}
    
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: unhashable type: 'list'

    Example 3

    You can assign a value to more than one keys in a dictionary, but a key cannot appear more than once in a dictionary.

    Open Compiler

    d1 ={“Banana”:”Fruit”,”Rose”:”Flower”,”Lotus”:”Flower”,”Mango”:”Fruit”} d2 ={“Fruit”:”Banana”,”Flower”:”Rose”,”Fruit”:”Mango”,”Flower”:”Lotus”}print(d1)print(d2)

    It will produce the following output −

    {'Banana': 'Fruit', 'Rose': 'Flower', 'Lotus': 'Flower', 'Mango': 'Fruit'}
    {'Fruit': 'Mango', 'Flower': 'Lotus'}
    

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

    Creating a Dictionary

    You can create a dictionary in Python by placing a comma-separated sequence of key-value pairs within curly braces {}, with a colon : separating each key and its associated value. Alternatively, you can use the dict() function.

    Example

    The following example demonstrates how to create a dictionary called “student_info” using both curly braces and the dict() function −

    Open Compiler

    # Creating a dictionary using curly braces
    sports_player ={"Name":"Sachin Tendulkar","Age":48,"Sport":"Cricket"}print("Dictionary using curly braces:", sports_player)# Creating a dictionary using the dict() function
    student_info =dict(name="Alice", age=21, major="Computer Science")print("Dictionary using dict():",student_info)

    The result produced is as shown below −

    Dictionary using curly braces: {'Name': 'Sachin Tendulkar', 'Age': 48, 'Sport': 'Cricket'}
    Dictionary using dict(): {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
    

    Accessing Dictionary Items

    You can access the value associated with a specific key using square brackets [] or the get() method −

    Open Compiler

    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Accessing values using square brackets
    name = student_info["name"]print("Name:",name)# Accessing values using the get() method
    age = student_info.get("age")print("Age:",age)

    The result obtained is as follows −

    Name: Alice
    Age: 21
    

    Modifying Dictionary Items

    You can modify the value associated with a specific key or add a new key-value pair −

    Open Compiler

    student_info ={"name":"Alice","age":21,"major":"Computer Science"}# Modifying an existing key-value pair
    student_info["age"]=22# Adding a new key-value pair
    student_info["graduation_year"]=2023print("The modified dictionary is:",student_info)

    Output of the above code is as follows −

    The modified dictionary is: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'graduation_year': 2023}
    

    Removing Dictionary Items

    You can remove items using the del statement, the pop() method, or the popitem() method −

    Open Compiler

    student_info ={"name":"Alice","age":22,"major":"Computer Science","graduation_year":2023}# Removing an item using the del statementdel student_info["major"]# Removing an item using the pop() method
    graduation_year = student_info.pop("graduation_year")print(student_info)

    Following is the output of the above code −

    {'name': 'Alice', 'age': 22}
    

    Iterating Through a Dictionary

    You can iterate through the keys, values, or key-value pairs in a dictionary using loops −

    Open Compiler

    student_info ={"name":"Alice","age":22,"major":"Computer Science","graduation_year":2023}# Iterating through keysfor key in student_info:print("Keys:",key, student_info[key])# Iterating through valuesfor value in student_info.values():print("Values:",value)# Iterating through key-value pairsfor key, value in student_info.items():print("Key:Value:",key, value)

    After executing the above code, we get the following output −

    Keys: name Alice
    Keys: age 22
    Keys: major Computer Science
    Keys: graduation_year 2023
    Values: Alice
    Values: 22
    Values: Computer Science
    Values: 2023
    Key:Value: name Alice
    Key:Value: age 22
    Key:Value: major Computer Science
    Key:Value: graduation_year 2023
    

    Properties of Dictionary Keys

    Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.

    There are two important points to remember about dictionary keys −

    • More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example −
    • Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed. Following is a simple example −

    Python Dictionary Operators

    In Python, following operators are defined to be used with dictionary operands. In the example, the following dictionary objects are used.

    d1 ={'a':2,'b':4,'c':30}
    d2 ={'a1':20,'b1':40,'c1':60}
    OperatorDescriptionExample
    dict[key]Extract/assign the value mapped with keyprint (d1[‘b’]) retrieves 4d1[‘b’] = ‘Z’ assigns new value to key ‘b’
    dict1|dict2Union of two dictionary objects, returning new objectd3=d1|d2 ; print (d3){‘a’: 2, ‘b’: 4, ‘c’: 30, ‘a1’: 20, ‘b1’: 40, ‘c1’: 60}
    dict1|=dict2Augmented dictionary union operatord1|=d2; print (d1){‘a’: 2, ‘b’: 4, ‘c’: 30, ‘a1’: 20, ‘b1’: 40, ‘c1’: 60}

    Python Dictionary Methods

    Python includes following dictionary methods −

    Sr.No.Methods with 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 key in dictionary dictfalse otherwise
    6dict.items()Returns a list of dict‘s (key, value) tuple pairs
    7dict.keys()Returns list of dictionary dict’s keys
    8dict.setdefault(key, default=None)Similar to get(), but will set dict[key]=default if key is not already in dict
    9dict.update(dict2)Adds dictionary dict2‘s key-values pairs to dict
    10dict.values()Returns list of dictionary dict‘s values

    Built-in Functions with Dictionaries

    Following are the built-in functions we can use with Dictionaries −

    Sr.No.Function with Description
    1cmp(dict1, dict2)Compares elements of both dict.
    2len(dict)Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
    3str(dict)Produces a printable string representation of a dictionary
    4type(variable)Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.
  •  Set Exercises

    Python Set Exercise 1

    Python program to find common elements in two lists with the help of set operations −

    Open Compiler

    l1=[1,2,3,4,5]
    l2=[4,5,6,7,8]
    s1=set(l1)
    s2=set(l2)
    commons = s1&s2 # or s1.intersection(s2)
    commonlist =list(commons)print(commonlist)

    It will produce the following output −

    [4, 5]
    

    Python Set Exercise 2

    Python program to check if a set is a subset of another −

    Open Compiler

    s1={1,2,3,4,5}
    s2={4,5}if s2.issubset(s1):print("s2 is a subset of s1")else:print("s2 is not a subset of s1")

    It will produce the following output −

    s2 is a subset of s1
    

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

    Python Set Exercise 3

    Python program to obtain a list of unique elements in a list −

    Open Compiler

    T1 =(1,9,1,6,3,4,5,1,1,2,5,6,7,8,9,2)
    s1 =set(T1)print(s1)

    It will produce the following output −

    {1, 2, 3, 4, 5, 6, 7, 8, 9}
  • E-commerce Platform

    Step 1: Set Up Your Environment

    Make sure you have Python installed, and then set up a virtual environment:

    mkdir ecommerce-platform
    cd ecommerce-platform
    python -m venv venv
    source venv/bin/activate  # On Windows use venv\Scripts\activate
    pip install Flask SQLAlchemy
    

    Step 2: Create the Project Structure

    Your project structure should look like this:

    arduinoCopy codeecommerce-platform/
    │
    ├── app.py
    ├── models.py
    ├── templates/
    │   ├── index.html
    │   ├── product.html
    │   └── cart.html
    └── static/
    
    └── style.css

    Step 3: Define the Models (models.py)

    Create a file named models.py for your database models.

    from flask_sqlalchemy import SQLAlchemy
    
    db = SQLAlchemy()
    
    class Product(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)
    description = db.Column(db.String(200), nullable=True)

    Step 4: Set Up the Application (app.py)

    Create a file named app.py for your application logic.

    from flask import Flask, render_template
    from models import db, Product
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    
    with app.app_context():
    
    db.create_all()
    @app.route('/') def index():
    products = Product.query.all()
    return render_template('index.html', products=products)
    @app.route('/product/<int:product_id>') def product(product_id):
    product = Product.query.get(product_id)
    return render_template('product.html', product=product)
    if __name__ == '__main__':
    app.run(debug=True)

    Step 5: Create the Frontend (HTML Templates)

    1. index.html
    <!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="/static/style.css">
    &lt;title>My E-Commerce Store&lt;/title>
    </head> <body>
    &lt;h1>Products&lt;/h1>
    &lt;ul>
        {% for product in products %}
        &lt;li>
            &lt;a href="{{ url_for('product', product_id=product.id) }}">{{ product.name }}&lt;/a>
            - ${{ product.price }}
        &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>
    1. product.html
    <!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="/static/style.css">
    &lt;title>{{ product.name }}&lt;/title>
    </head> <body>
    &lt;h1>{{ product.name }}&lt;/h1>
    &lt;p>{{ product.description }}&lt;/p>
    &lt;p>Price: ${{ product.price }}&lt;/p>
    &lt;a href="/">Back to products&lt;/a>
    </body> </html>
    1. cart.html (Optional for future expansion)

    You can expand this later with cart functionality.

    Step 6: Add Some Styles (style.css)

    Create a file named style.css in the static folder for basic styling.

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

    Step 7: Running the Application

    To run your application, use the following command:

    bashCopy codepython app.py
    

    Visit http://127.0.0.1:5000 in your browser to see your e-commerce platform!

  •  Set Exercises

    Python Set Exercise 1

    Python program to find common elements in two lists with the help of set operations −

    Open Compiler

    l1=[1,2,3,4,5]
    l2=[4,5,6,7,8]
    s1=set(l1)
    s2=set(l2)
    commons = s1&s2 # or s1.intersection(s2)
    commonlist =list(commons)print(commonlist)

    It will produce the following output −

    [4, 5]
    

    Python Set Exercise 2

    Python program to check if a set is a subset of another −

    Open Compiler

    s1={1,2,3,4,5}
    s2={4,5}if s2.issubset(s1):print("s2 is a subset of s1")else:print("s2 is not a subset of s1")

    It will produce the following output −

    s2 is a subset of s1
    

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

    Python Set Exercise 3

    Python program to obtain a list of unique elements in a list −

    Open Compiler

    T1 =(1,9,1,6,3,4,5,1,1,2,5,6,7,8,9,2)
    s1 =set(T1)print(s1)

    It will produce the following output −

    {1, 2, 3, 4, 5, 6, 7, 8, 9}
  • Set Methods

    Sets in Python are unordered collections of unique elements, often used for membership testing and eliminating duplicates. Set objects support various mathematical operations like union, intersection, difference, and symmetric difference. The set class includes several built-in methods that allow you to add, update, and delete elements efficiently, as well as to perform various set operations such as union, intersection, difference, and symmetric difference on elements.

    Understanding Set Methods

    The set methods provide convenient ways to manipulate sets, allowing users to add or remove elements, perform set operations, and check for membership and relationships between sets. You can view all available methods for sets, using the Python dir() function to list all properties and functions related to the set class. Additionally, the help() function provides detailed documentation for each method.

    Python Set Methods

    Below are the built-in methods for sets in Python, categorized based on their functionality. Let’s explore and understand the basic functionality of each method.

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

    Adding and Removing Elements

    The following are the methods specifically designed for adding and removing item/items into a set −

    Sr.No.Methods with Description
    1set.add()Add an element to a set.
    2set.clear()Remove all elements from a set.
    3set.copy()Return a shallow copy of a set.
    4set.discard()Remove an element from a set if it is a member.
    5set.pop()Remove and return an arbitrary set element.
    6set.remove()Remove an element from a set; it must be a member.

    Set Operations

    These methods perform set operations such as union, intersection, difference, and symmetric difference −

    Sr.No.Methods with Description
    1set.update()Update a set with the union of itself and others.
    2set.difference_update()Remove all elements of another set from this set.
    3set.intersection()Returns the intersection of two sets as a new set.
    4set.intersection_update()Updates a set with the intersection of itself and another.
    5set.isdisjoint()Returns True if two sets have a null intersection.
    6set.issubset()Returns True if another set contains this set.
    7set.issuperset()Returns True if this set contains another set.
    8set.symmetric_difference()Returns the symmetric difference of two sets as a new set.
    9set.symmetric_difference_update()Update a set with the symmetric difference of itself and another.
    10set.union()Returns the union of sets as a new set.
    11set.difference()Returns the difference of two or more sets as a new set.