ASSIGNMENT

ASSIGNMENT

Q.6 How to create Dictionary in Python? Discuss various methods with example.

Answer :- 

  • A dictionary in Python is an unordered, mutable, and indexed collection used to store data in the form of key-value pairs.
  • Each key in a dictionary must be unique and immutable (e.g., strings, numbers, or tuples), while values can be of any type and can repeat.


Syntax of a Dictionary

  • A dictionary is defined using curly braces {} with key-value pairs separated by colons

  • my_dict = {key1: value1, key2: value2, …}

Creating a Dictionary

  • Using Curly Braces {}
    my_dict = {“name”: “Alice”, “age”: 25, “city”: “New York”}
    print(my_dict)
    # Output: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
  • Using the dict()
    my_dict = dict(name=”Alice”, age=25, city=”New York”)
    print(my_dict)
    # Output: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
  • From a List of Tuples
    my_dict = dict([(“name”, “Alice”), (“age”, 25), (“city”, “New York”)])
    print(my_dict)
    # Output: {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
  • Using Dictionary Comprehension
    my_dict = {x: x**2 for x in range(1, 4)}
    print(my_dict)
    # Output: {1: 1, 2: 4, 3: 9}

Dictionary Methods

Python provides several built-in methods for performing operations on dictionaries. Below are the most common methods with examples:
  • keys()

    Purpose: Returns a view object of all the keys in the dictionary.
    Example:
    my_dict = {“name”: “Alice”, “age”: 25}
    print(my_dict.keys())
    # Output: dict_keys([‘name’, ‘age’])
  • values()

    Purpose: Returns a view object of all the values in the dictionary.
    Example:-
    my_dict = {“name”: “Alice”, “age”: 25}
    print(my_dict.values())
    # Output: dict_values([‘Alice’, 25])
  • items()

    Purpose: Returns a view object of all key-value pairs as tuples.
    Example:-
    my_dict = {“name”: “Alice”, “age”: 25}
    print(my_dict.items())
    # Output: dict_items([(‘name’, ‘Alice’), (‘age’, 25)])
  • get()

    Purpose: Returns the value of the specified key. If the key does not exist, it returns None (or a specified default value).
    Example:-
    my_dict = {“name”: “Alice”, “age”: 25}
    print(my_dict.get(“name”)) # Output: Alice
    print(my_dict.get(“city”, “Not Found”)) # Output: Not Found
  • update()

    Purpose: Updates the dictionary with key-value pairs from another dictionary or iterable.
    Example :-
    my_dict = {“name”: “Alice”, “age”: 25}
    my_dict.update({“city”: “New York”, “age”: 26})
    print(my_dict)
    # Output: {‘name’: ‘Alice’, ‘age’: 26, ‘city’: ‘New York’}
  • pop()

    Purpose: Removes the specified key and returns its value. Raises a KeyError if the key does not exist.
    Example :-
    my_dict = {“name”: “Alice”, “age”: 25}
    age = my_dict.pop(“age”)
    print(age) # Output: 25
    print(my_dict) # Output: {‘name’: ‘Alice’}
  • popitem()

    Purpose: Removes and returns the last inserted key-value pair as a tuple.
    Example :-
    my_dict = {“name”: “Alice”, “age”: 25}
    item = my_dict.popitem()
    print(item) # Output: (‘age’, 25)
    print(my_dict) # Output: {‘name’: ‘Alice’}
  • clear()

    Purpose: Removes all items from the dictionary.
    Example :-
    my_dict = {“name”: “Alice”, “age”: 25}
    my_dict.clear()
    print(my_dict) # Output: {}
  • copy()

    Purpose: Returns a shallow copy of the dictionary.
    Example :-
    my_dict = {“name”: “Alice”, “age”: 25}
    copied_dict = my_dict.copy()
    print(copied_dict)
    # Output: {‘name’: ‘Alice’, ‘age’: 25}
  • setdefault()

    Purpose: Returns the value of the specified key. If the key does not exist, it inserts the key with a specified default value.
    Example :-
    my_dict = {“name”: “Alice”}
    city = my_dict.setdefault(“city”, “Unknown”)
    print(city) # Output: Unknown
    print(my_dict) # Output: {‘name’: ‘Alice’, ‘city’: ‘Unknown’}

Example of Dictionary

  • # Create a dictionary
    student = {“name”: “John”, “age”: 20, “course”: “Computer Science”}
    # Access keys, values, and items
    print(student.keys()) # dict_keys([‘name’, ‘age’, ‘course’])
    print(student.values()) # dict_values([‘John’, 20, ‘Computer Science’])
    print(student.items()) # dict_items([(‘name’, ‘John’), (‘age’, 20), (‘course’, ‘Computer Science’)])
    # Update dictionary
    student.update({“age”: 21, “grade”: “A”})
    print(student)
    # {‘name’: ‘John’, ‘age’: 21, ‘course’: ‘Computer Science’, ‘grade’: ‘A’}
    # Remove an item
    removed = student.pop(“course”)
    print(removed) # Output: Computer Science
    print(student)
    # {‘name’: ‘John’, ‘age’: 21, ‘grade’: ‘A’}
 

Leave a Reply

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

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.