Dictionary
What is a Dictionary?
- A dictionary is an unordered, mutable collection of key-
value pairs.
- Keys must be unique and immutable.
- Values can be of any data type.
Example:
d = {"name": "Alice", "age": 25, "city": "Chennai"}
Creating Dictionaries
# Using curly braces
d = {"fruit": "apple", "count": 5}
# Using dict() constructor
d2 = dict(name="Bob", age=30) //No quotes for string key
#Using key as index
squares={}
squares[‘one’]=1
squares[‘two’]=4
Accessing Values
print(d["fruit"]) # Output: apple
print([Link]("count")) # Output: 5
- get() returns None if the key doesn't exist
Modifying Dictionaries
d["count"] = 10 # Update value
d["color"] = "red" # Add new key-value pair
[Link]("fruit") # Remove key-value pair
Dictionary Methods
keys() - Returns all keys
values() - Returns all values
items() - Returns all key-value pairs
get(key) - Returns value or None
pop(key) - Removes and returns value by key
update(dict) - Adds/updates another dictionary
Looping through Dictionary
for key in d:
print(key, d[key])
for key, value in [Link]():
print(key, value)
Dictionary Comprehension
squares = {x: x*x for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
items()
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science"
}
# Using items() to loop through key-value pairs
for key, value in [Link]():
print(key, ":", value)
fromkeys()
The fromkeys() method is used to create a new dictionary with the specified keys and a common
default value.
◦keys = ["name", "age", "gender"]
◦d = [Link](keys,0)
◦print(d)
Example
employees = {
"Alice": 50000,
"Bob": 60000,
}
salaries = [Link]()
if salaries:
average = sum(salaries) / len(salaries)
print("Average Salary:", average)
else:
print("No salaries to compute.")
Example
shopping_cart = {
"T-shirt": 499,
"Jeans": 1299,
}
total = 0
print("Shopping Cart:")
for item, price in shopping_cart.items():
print(f"{item} - ₹{price}")
total += price
print("\nTotal Bill Amount: ₹", total)
Practice Questions
1. Create a dictionary to store and display employee details.
name,empid and dept
2. Write a program to count word frequency in a sentence.
sent=input()
x=[Link]()
d={}
for y in x:
d[y]=[Link](y,0)+1 //get the value of key y [0 by default]
print(d)
d[y]=[Link](y,0)+1
#get the value of key y [0 by
default]
Summary
- Dictionaries store data in key-value pairs.
- Keys must be unique and immutable.
- Powerful for fast lookups and organizing structured data.