Dictionaries are a fundamental data structure in Python that allow us to store and organize data in a flexible and efficient manner. Unlike lists and tuples, which use an index-based approach, dictionaries use a key-value pairing system. In this article, we will explore dictionaries in Python, understand their properties, and demonstrate their usage through examples.
-
Creating Dictionaries:
-
Example 1: Creating a dictionary using curly braces and key-value pairs
student = {"name": "John", "age": 20, "major": "Computer Science"} -
Example 2: Creating a dictionary using the
dict()constructor and keyword argumentsstudent = dict(name="John", age=20, major="Computer Science")
-
-
Accessing Values:
-
Example 1: Accessing a value using the key
student = {"name": "John", "age": 20, "major": "Computer Science"}print(student["name"])# Output: John -
Example 2: Using the
get()method to access a value with a default fallbackstudent = {"name": "John", "age": 20, "major": "Computer Science"}print(student.get("gender", "Unknown"))# Output: Unknown
-
-
Modifying and Adding Elements:
-
Example 1: Modifying a value by accessing it using the key
student = {"name": "John", "age": 20, "major": "Computer Science"}student["age"] = 21print(student["age"])# Output: 21 -
Example 2: Adding a new key-value pair to the dictionary
student = {"name": "John", "age": 20}student["major"] = "Computer Science"print(student)# Output: {'name': 'John', 'age': 20, 'major': 'Computer Science'}
-
-
Iterating over Dictionaries:
- Example: Iterating through the keys and values of a dictionary using a for loop
student = {"name": "John", "age": 20, "major": "Computer Science"}for key, value in student.items():print(key, ":", value)# Output: # name : John # age : 20 # major : Computer Science
- Example: Iterating through the keys and values of a dictionary using a for loop
-
Dictionary Methods:
- Example: Using the
keys(),values(), anditems()methodsstudent = {"name": "John", "age": 20, "major": "Computer Science"}print(student.keys())# Output: dict_keys(['name', 'age', 'major']) print(student.values())# Output: dict_values(['John', 20, 'Computer Science'])print(student.items())# Output: dict_items([('name', 'John'), ('age', 20), ('major', 'Computer Science')])
- Example: Using the
Conclusion: Dictionaries are a versatile and powerful data structure in Python, allowing us to store and retrieve data using key-value pairs. They offer fast access and efficient modification, making them suitable for various use cases. By mastering dictionaries, you can effectively organize and manipulate data, simplifying your code and enhancing your Python programming skills