Site icon DataFlair

Python Program on Dictionary

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we will delve into the world of dictionaries, a versatile and powerful data type in Python. The program presented focuses on dictionary operations, demonstrating how to initialize a dictionary, modify its values, and retrieve information from it. By exploring this example, readers will gain practical insights into the use of dictionaries and how they contribute to efficient data manipulation in Python.

Prerequisites

Topic Explanation

The program initializes a dictionary, mydict, with key-value pairs representing student IDs and names. It showcases the uniqueness of keys in dictionaries and demonstrates how to modify the value associated with a specific key. The example highlights the dynamic nature of dictionaries, where values can be updated or replaced easily.

In addition to showcasing the uniqueness of keys and demonstrating value modification in dictionaries, the program also introduces the concept of dynamic dictionary behavior. It further emphasizes the ease with which values can be updated or replaced, providing a comprehensive understanding of the practical aspects of working with dictionaries in Python.

Code:

# Initialize a dictionary 'mydict' with key-value pairs
mydict = {101: 'Rahul', 102: 'Anil Sharma', 103: 'Nilesh', 104: 'Rahul'}

# Update the value associated with key 101 in the dictionary
mydict[101] = "Anurag Verma"

# Print the updated dictionary
print(mydict)

# Print the values of the dictionary using the values() method
print(mydict.values())
Output:
{101: ‘Anurag Verma’, 102: ‘Anil Sharma’, 103: ‘Nilesh’, 104: ‘Rahul’}
dict_values([‘Anurag Verma’, ‘Anil Sharma’, ‘Nilesh’, ‘Rahul’])

Code Explanation:

Summary

In summary, this article provides a comprehensive exploration of Python dictionaries, exemplifying their versatility through a practical program example. The presented program initializes a dictionary containing student information, emphasizing the importance of key uniqueness and demonstrating efficient methods for value updates. Readers will gain practical insights into the dynamic nature of dictionaries, greatly enhancing their understanding of effective data manipulation in Python.

Exit mobile version