DEV Community

Haripriya V
Haripriya V

Posted on

Task – Annachi Kadai – Python Dictionary

1.Create a dictionary named student with the following keys and values. and print the same
"name": "Alice"
"age": 21
"major": "Computer Science"

CODE:

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

OUTPUT:

{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

EXPLANATION:

  • A dictionary stores data as key-value pairs

  • Keys: name, age, major

2.Using the student dictionary, print the values associated with the keys "name" and "major".

CODE:

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

OUTPUT:

Alice
Computer Science

EXPLANATION:

  • Use keys to access values

3.Add a new key-value pair to the student dictionary: "gpa": 3.8. Then update the "age" to 22.

CODE:

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

OUTPUT:

{'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'gpa': 3.8}

EXPLANATION:

  • New key added

  • Existing key updated

4.Remove the key "major" from the student dictionary using the del statement. Print the dictionary to confirm the removal.

CODE:

del student["major"]
print(student)

OUTPUT:

{'name': 'Alice', 'age': 22, 'gpa': 3.8}

EXPLANATION:

  • del removes a key-value pair

5.Check if the key "age" exists in the student dictionary. Print True or False based on the result.

CODE:

print("age" in student)

OUTPUT:

True

EXPLANATION:

  • in checks if key exists

6.Create a dictionary prices with three items, e.g., "apple": 0.5, "banana": 0.3, "orange": 0.7. Iterate over the dictionary and print each key-value pair.

CODE:

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

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

OUTPUT:

apple 0.5
banana 0.3
orange 0.7

EXPLANATION:

  • .items() gives key-value pairs

7.Use the len() function to find the number of key-value pairs in the prices dictionary. Print the result.

CODE:

print(len(prices))

OUTPUT:

3

EXPLANATION:

  • len() counts key-value pairs

8.Use the get() method to access the "gpa" in the student dictionary. Try to access a non-existing key, e.g., "graduation_year", with a default value of 2025.

CODE:

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

OUTPUT:

3.8
2025

EXPLANATION:

  • get() avoids errors

  • Default value used if key missing

9.Create another dictionary extra_info with the following keys and values. Also merge extra_info into the student dictionary using the update() method.
"graduation_year": 2025
"hometown": "Springfield"

CODE:

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

student.update(extra_info)
print(student)`

OUTPUT:

{'name': 'Alice', 'age': 22, 'gpa': 3.8, 'graduation_year': 2025, 'hometown': 'Springfield'}

EXPLANATION:

  • update() merges dictionaries

10.Create a dictionary squares where the keys are numbers from 1 to 5 and the values are the squares of the keys. Use dictionary comprehension.

CODE:

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

OUTPUT:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

EXPLANATION:

  • Creates dictionary dynamically

11.Using the prices dictionary, print the keys and values as separate lists using the keys() and values() methods.

CODE:

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

OUTPUT:

['apple', 'banana', 'orange']
[0.5, 0.3, 0.7]

EXPLANATION:

  • .keys() and .values() extract data

12.Create a dictionary school with two nested dictionaries. Access and print the age of "student2".
"student1": {"name": "Alice", "age": 21}
"student2": {"name": "Bob", "age": 22}

CODE:

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

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

OUTPUT:

22

EXPLANATION:

  • Access nested dictionary using multiple keys

13.Use the setdefault() method to add a new key "advisor" with the value "Dr. Smith" to the student dictionary if it does not exist.

CODE:

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

OUTPUT:

{'name': 'Alice', 'age': 22, 'gpa': 3.8, 'graduation_year': 2025, 'hometown': 'Springfield', 'advisor': 'Dr. Smith'}

EXPLANATION:

  • Adds key only if it doesn’t exist

14.Use the pop() method to remove the "hometown" key from the student dictionary and store its value in a variable. Print the variable.

CODE:

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

OUTPUT:

Springfield

EXPLANATION:

  • pop() removes and returns value

15.Use the clear() method to remove all items from the prices dictionary. Print the dictionary to confirm it’s empty.

CODE:

prices.clear()
print(prices)

OUTPUT:

{}

EXPLANATION:

  • Removes all items

16.Make a copy of the student dictionary using the copy() method. Modify the copy by changing "name" to "Charlie". Print both dictionaries to see the differences.

CODE:

`copy_student = student.copy()
copy_student["name"] = "Charlie"

print(student)
print(copy_student)`

OUTPUT:

{'name': 'Alice', ...}
{'name': 'Charlie', ...}

EXPLANATION:

  • Copy creates separate dictionary

17.Create two lists: keys = ["name", "age", "major"] and values = ["Eve", 20, "Mathematics"]. Use the zip() function to create a dictionary from these lists.

CODE:

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

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

OUTPUT:

{'name': 'Eve', 'age': 20, 'major': 'Mathematics'}

EXPLANATION:

  • zip() pairs elements

18.Use the items() method to iterate over the student dictionary and print each key-value pair.

CODE:

for k, v in student.items():
print(k, v)

OUTPUT:

name Alice
age 22
...

EXPLANATION:

  • Iterates over key-value pairs

19.Given a list of fruits: ["apple", "banana", "apple", "orange", "banana", "banana"], create a dictionary fruit_count that counts the occurrences of each fruit.

CODE:

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

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

print(fruit_count)`

OUTPUT:

{'apple': 2, 'banana': 3, 'orange': 1}

EXPLANATION:

  • Counts occurrences using dictionary

20.Use collections.defaultdict to create a dictionary word_count that counts the number of occurrences of each word in a list: ["hello", "world", "hello", "python"].

CODE:

`from collections import defaultdict

words = ["hello", "world", "hello", "python"]
word_count = defaultdict(int)

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

print(dict(word_count))`

OUTPUT:

{'hello': 2, 'world': 1, 'python': 1}

EXPLANATION:

  • defaultdict(int) sets default value to 0

Top comments (0)