Author: Saim Khalid

  • Remove Array Items

    Removing array items in Python

    Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

    The array module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

    Python does not provide built-in support for arrays, however, we can use the array module to achieve the functionality like an array.

    Remove First Occurrence

    To remove the first occurrence of a given value from the array, use remove() method. This method accepts an element and removes it if the element is available in the array.

    Syntax

    array.remove(v)

    Where, v is the value to be removed from the array.

    Example

    The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.remove(311)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 411, 511])
    

    Remove Items from Specific Indices

    To remove an array element from specific index, use the pop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

    Syntax

    array.pop(i)

    Where, i is the index for the element to be removed.

    Example

    In this example, we will see how to use pop() method to remove elements from an array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.pop(3)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 311, 511])
  • Add Array Items

    Python array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.

    Python does not have built-in support for arrays, it uses array module to achieve the functionality like an array.

    Adding Elements to Python Array

    There are multiple ways to add elements to an array in Python −

    • Using append() method
    • Using insert() method
    • Using extend() method

    Using append() method

    To add a new element to an array, use the append() method. It accepts a single item as an argument and append it at the end of given array.

    Syntax

    Syntax of the append() method is as follows −

    append(v)

    Where,

    • v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

    Example

    Here, we are adding element at the end of specified array using append() method.

    import array as arr
    a = arr.array('i',[1,2,3])
    a.append(10)print(a)

    It will produce the following output −

    array('i', [1, 2, 3, 10])
    

    Using insert() method

    It is possible to add a new element at the specified index using the insert() method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.

    Syntax

    Syntax of this method is shown below −

    insert(i, v)

    Where,

    • i − The index at which new value is to be inserted.
    • v − The value to be inserted. Must be of the arraytype.

    Example

    The following example shows how to add array elements at specific index with the help of insert() method.

    import array as arr
    a = arr.array('i',[1,2,3])
    a.insert(1,20)print(a)

    It will produce the following output −

    array('i', [1, 20, 2, 3])
    

    Using extend() method

    The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.

    Syntax

    This method has the following syntax −

    extend(x)

    Where,

    • x − This parameter specifies an array or iterable.

    Example

    In this example, we are adding items from another array to the specified array.

    import array as arr
    a = arr.array('i',[1,2,3,4,5])
    b = arr.array('i',[6,7,8,9,10])
    a.extend(b)print(a)

    On executing the above code, it will produce the following output −

    array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    
  • Access Array Items

    Accessing an array items in Python refers to the process of retrieving the value stored at a specific index in the given array. Here, index is an numerical value that indicates the location of array items. Thus, you can use this index to access elements of an array in Python.

    An array is a container that holds a fix number of items of the same type. Python uses array module to achieve the functionality like an array.

    Accessing array items in Python

    You can use the following ways to access array items in Python −

    • Using indexing
    • Using iteration
    • Using enumerate() function

    Using indexing

    The process of accessing elements of an array through the index is known as Indexing. In this process, we simply need to pass the index number inside the index operator []. The index of an array in Python starts with 0 which means you can find its first element at index 0 and the last at one less than the length of given array.

    Example

    The following example shows how to access elements of an array using indexing.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])#indexingprint(numericArray[0])print(numericArray[1])print(numericArray[2])

    When you run the above code, it will show the following output −

    111
    211
    311
    

    Using iteration

    In this approach, a block of code is executed repeatedely using loops such as for and while. It is used when you want to access array elements one by one.

    Example

    In the below code, we use the for loop to access all the elements of the specified array.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# iteration through for loopfor item in numericArray:print(item)

    On executing the above code, it will display the following result −

    111
    211
    311
    411
    511
    

    Using enumerate() function

    The enumerate() function can be used to access elements of an array. It accepts an array and an optional starting index as parameter values and returns the array items by iterating.

    Example

    In the below example, we will see how to use the enumerate() function to access array items.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# use of enumerate() functionfor loc, val inenumerate(numericArray):print(f"Index: {loc}, value: {val}")

    It will produce the following output −

    Index: 0, value: 111
    Index: 1, value: 211
    Index: 2, value: 311
    Index: 3, value: 411
    Index: 4, value: 511
    

    Accessing a range of array items in Python

    In Python, to access a range of array items, you can use the slicing operation which is performed using index operator [] and colon (:).

    This operation is implemented using multiple formats, which are listed below −

    • Use the [:index] format to access elements from beginning to desired range.
    • To access array items from end, use [:-index] format.
    • Use the [index:] format to access array items from specific index number till the end.
    • Use the [start index : end index] to slice the array elements within a range. You can also pass an optional argument after end index to determine the increment between each index.

    Example

    The following example demonstrates the slicing operation in Python.

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# slicing operationprint(numericArray[2:])print(numericArray[0:3])

    On executing the above code, it will display the following result −

    array('i', [311, 411, 511])
    array('i', [111, 211, 311])
    
  • Arrays

    Arrays in Python

    Unlike other programming languages like C++ or Java, Python does not have built-in support for arrays. However, Python has several data types like lists and tuples (especially lists) that are often used as arrays but, items stored in these types of sequences need not be of the same type.

    In addition, we can create and manipulate arrays the using the array module. Before proceeding further, let’s understand arrays in general.

    What are arrays?

    An array is a container which can hold a fix number of items and these items should be of the same type. Each item stored in an array is called an element and they can be of any type including integers, floats, strings, etc.

    These elements are stored at contiguous memory location. Each location of an element in an array has a numerical index starting from 0. These indices are used to identify and access the elements.

    Array Representation

    Arrays are represented as a collection of multiple containers where each container stores one element. These containers are indexed from ‘0’ to ‘n-1’, where n is the size of that particular array.

    Arrays can be declared in various ways in different languages. Below is an illustration −

    Python Array Representation

    As per the above illustration, following are the important points to be considered −

    • Index starts with 0.
    • Array length is 10 which means it can store 10 elements.
    • Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.

    Creating Array in Python

    To create an array in Python, import the array module and use its array() function. We can create an array of three basic types namely integer, float and Unicode characters using this function.

    The array() function accepts typecode and initializer as a parameter value and returns an object of array class.

    Syntax

    The syntax for creating an array in Python is −

    # importing import array as array_name
    
    # creating array
    obj = array_name.array(typecode[, initializer])

    Where,

    • typecode − The typecode character used to speccify the type of elements in the array.
    • initializer − It is an optional value from which array is initialized. It must be a list, a bytes-like object, or iterable elements of the appropriate type.

    Example

    The following example shows how to create an array in Python using the array module.

    import array as arr
    
    # creating an array with integer type
    a = arr.array('i',[1,2,3])print(type(a), a)# creating an array with char type
    a = arr.array('u','BAT')print(type(a), a)# creating an array with float type
    a = arr.array('d',[1.1,2.2,3.3])print(type(a), a)

    It will produce the following output −

    <class 'array.array'> array('i', [1, 2, 3])
    <class 'array.array'> array('u', 'BAT')
    <class 'array.array'> array('d', [1.1, 2.2, 3.3])
    

    Python array type is decided by a single character Typecode argument. The type codes and the intended data type of array is listed below −

    typecodePython data typeByte size
    ‘b’signed integer1
    ‘B’unsigned integer1
    ‘u’Unicode character2
    ‘h’signed integer2
    ‘H’unsigned integer2
    ‘i’signed integer2
    ‘I’unsigned integer2
    ‘l’signed integer4
    ‘L’unsigned integer4
    ‘q’signed integer8
    ‘Q’unsigned integer8
    ‘f’floating point4
    ‘d’floating point8

    Basic Operations on Python Arrays

    Following are the basic operations supported by an array −

    • Traverse − Print all the array elements one by one.
    • Insertion − Adds an element at the given index.
    • Deletion − Deletes an element at the given index.
    • Search − Searches an element using the given index or by the value.
    • Update − Updates an element at the given index.

    Accessing Array Element

    We can access each element of an array using the index of the element.

    Example

    The below code shows how to access elements of an array.

    from array import*
    array1 = array('i',[10,20,30,40,50])print(array1[0])print(array1[2])

    When we compile and execute the above program, it produces the following result −

    10
    30
    

    Insertion Operation

    In insertion operation, we insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array.

    Example

    Here, we add a data element at the middle of the array using the python in-built insert() method.

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1.insert(1,60)for x in array1:print(x)

    When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1.

    10
    60
    20
    30
    40
    50
    

    Deletion Operation

    Deletion refers to removing an existing element from the array and re-organizing all elements of an array.

    Here, we remove a data element at the middle of the array using the python in-built remove() method.

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1.remove(40)for x in array1:print(x)

    When we compile and execute the above program, it produces the following result which shows the element is removed form the array.

    10
    20
    30
    50
    

    Search Operation

    You can perform a search operation on an array to find an array element based on its value or its index.

    Example

    Here, we search a data element using the python in-built index() method −

    from array import*
    array1 = array('i',[10,20,30,40,50])print(array1.index(40))

    When we compile and execute the above program, it will display the index of the searched element. If the value is not present in the array, it will return an error.

    3
    

    Update Operation

    Update operation refers to updating an existing element from the array at a given index. Here, we simply reassign a new value to the desired index we want to update.

    Example

    In this example, we are updating the value of array element at index 2.

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1[2]=80for x in array1:print(x)

    On executing the above program, it produces the following result which shows the new value at the index position 2.

    10
    20
    80
    40
    50
  • Dictionary Exercises

    Dictionary Exercise 1

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

    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.

    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)]
    Dictionary Exercise 3
    Python program to remove keys with same values in a dictionary.

    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)
    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 −

    # 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 −

    # 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)

    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 −

    # 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 −

    # 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) −

    # 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 −

    # 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 −

    # 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.

    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 −

    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#']}
    

    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 −

    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 −

    # 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 −

    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 −

    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
    

    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” −

    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 −

    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 −

    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.

    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 −

    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])
    

    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 −

    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'])