ANNACHI KADAI

 

Annachi Kadai – Python Dictionary Operations 

Introduction

Dictionaries in Python are used to store data in key-value pairs. They are useful when we need to associate values with unique keys. In this task, various dictionary operations are performed to understand how to create, modify, and manipulate dictionaries efficiently.

1. Creating and printing a dictionary

student = {
    "name": "Alice",
    "age": 21,
    "major": "Computer Science"
}
print(student)

Approach: Dictionary creation using curly braces
Why: This is the standard and most readable way to define key-value pairs.

2. Accessing specific values

print(student["name"])
print(student["major"])

Approach: Direct key access
Why: Fast and simple when we are sure the key exists.
Alternative: get() method for safer access.

3. Adding and updating values

student["gpa"] = 3.8
student["age"] = 22
print(student)

Approach: Direct assignment
Why: Dictionaries allow easy addition and updating using keys.

4. Removing a key

del student["major"]
print(student)

Approach: del statement
Why: Used to completely remove a key-value pair from the dictionary.

5. Checking key existence

print("age" in student)

Approach: Membership operator
Why: Efficient way to check if a key exists.

6. Iterating through a dictionary

prices = {"apple": 0.5, "banana": 0.3, "orange": 0.7}

for key, value in prices.items():
    print(key, value)

Approach: Using items()
Why: Allows access to both key and value together in a clean way.

7. Finding dictionary length

print(len(prices))

Approach: len() function
Why: Returns total number of key-value pairs.

8. Using get() method

print(student.get("gpa"))
print(student.get("graduation_year", 2025))

Approach: get() method
Why: Prevents errors if the key does not exist and allows default values.

9. Merging dictionaries

extra_info = {
    "graduation_year": 2025,
    "hometown": "Springfield"
}

student.update(extra_info)
print(student)

Approach: update() method
Why: Efficient way to merge two dictionaries.

10. Dictionary comprehension

squares = {x: x*x for x in range(1, 6)}
print(squares)

Approach: Dictionary comprehension
Why: Compact and readable way to generate dictionaries.

11. Getting keys and values separately

print(list(prices.keys()))
print(list(prices.values()))

Approach: keys() and values()
Why: Useful when we need separate lists of keys or values.

12. Nested dictionaries

school = {
    "student1": {"name": "Alice", "age": 21},
    "student2": {"name": "Bob", "age": 22}
}

print(school["student2"]["age"])

Approach: Nested dictionary access
Why: Helps store structured data.

13. Using setdefault()

student.setdefault("advisor", "Dr. Smith")
print(student)

Approach: setdefault()
Why: Adds key only if it does not already exist.

14. Using pop()

value = student.pop("hometown")
print(value)

Approach: pop() method
Why: Removes key and returns its value.

15. Clearing dictionary

prices.clear()
print(prices)

Approach: clear() method
Why: Removes all elements efficiently.

16. Copying a dictionary

student_copy = student.copy()
student_copy["name"] = "Charlie"

print(student)
print(student_copy)

Approach: copy() method
Why: Creates a separate copy to avoid modifying original data.

17. Creating dictionary using zip()

keys = ["name", "age", "major"]
values = ["Eve", 20, "Mathematics"]

new_dict = dict(zip(keys, values))
print(new_dict)

Approach: zip() function
Why: Combines two lists into a dictionary efficiently.

18. Iterating using items()

for key, value in student.items():
    print(key, value)

Approach: items() method
Why: Best way to iterate over both keys and values.

19. Counting occurrences

fruits = ["apple", "banana", "apple", "orange", "banana", "banana"]

fruit_count = {}
for fruit in fruits:
    fruit_count[fruit] = fruit_count.get(fruit, 0) + 1

print(fruit_count)

Approach: Using get() for counting
Why: Avoids key errors and simplifies counting logic.

20. Using defaultdict

from collections import defaultdict

words = ["hello", "world", "hello", "python"]

word_count = defaultdict(int)

for word in words:
    word_count[word] += 1

print(dict(word_count))

Approach: defaultdict
Why: Automatically initializes values, making counting easier than normal dictionaries.

Conclusion

This task covers various dictionary operations such as creation, updating, merging, and iteration. Different approaches like get(), update(), and dictionary comprehension improve code readability and efficiency. Choosing the right method depends on the requirement and helps in writing clean and maintainable code.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT