In Python, a Dictionary is a built-in data type used to store data in the form of key-value pairs.
Each key is unique and is used to access its corresponding value. Dictionaries are mutable, which means we can add, update and delete elements after creation.
Dictionaries are useful for storing structured information such as student details, employee records, product information and much more.
1. Creating a Dictionary
A dictionary is created using curly brackets {} with key-value pairs separated by commas.
d = {
"name": "Alice",
"age": 25,
"city": "Chennai"
}
print(d)
print(type(d))
print(len(d))
Output:
{'name': 'Alice', 'age': 25, 'city': 'Chennai'}
<class 'dict'>
3
Explanation:
-
{}is used to create a dictionary. - Each key is separated from its value using a colon
:. -
type()identifies the data type. -
len()returns the number of key-value pairs.
2. Accessing Dictionary Values
We can access dictionary values using their keys.
d = {
"name": "Alice",
"age": 25,
"city": "Chennai"
}
print(d["name"])
print(d["age"])
Output:
Alice
25
Using get():
The get() method returns the value associated with a key.
d = {"name": "Alice", "age": 25}
print(d.get("name"))
print(d.get("salary"))
Output:
Alice
None
Explanation: If a key does not exist, get() returns None by default instead of raising a KeyError.
3. Adding Elements to a Dictionary
We can add new key-value pairs by assigning a value to a new key.
d = {"name": "Alice"}
d["age"] = 25
d["city"] = "Chennai"
print(d)
Output:
{'name': 'Alice', 'age': 25, 'city': 'Chennai'}
4. Updating Dictionary Values
We can modify existing values using their keys.
d = {
"name": "Alice",
"age": 25
}
d["age"] = 26
print(d)
Output:
{'name': 'Alice', 'age': 26}
Using update():
The update() method adds new key-value pairs or updates existing ones.
d = {"name": "Alice", "age": 25}
d.update({"age": 26, "city": "Chennai"})
print(d)
Output:
{'name': 'Alice', 'age': 26, 'city': 'Chennai'}
5. Removing Elements from a Dictionary
Python provides different methods to remove dictionary elements.
Using pop():
Removes a specified key and returns its value.
d = {"name": "Alice", "age": 25, "city": "Chennai"}
d.pop("age")
print(d)
Output:
{'name': 'Alice', 'city': 'Chennai'}
Using popitem():
Removes and returns the last inserted key-value pair.
d = {"name": "Alice", "age": 25, "city": "Chennai"}
print(d.popitem())
print(d)
Output:
('city', 'Chennai')
{'name': 'Alice', 'age': 25}
Using del:
d = {"name": "Alice", "age": 25}
del d["age"]
print(d)
Output:
{'name': 'Alice'}
Using clear():
Removes all elements from the dictionary.
d = {"name": "Alice", "age": 25}
d.clear()
print(d)
Output:
{}
6. Dictionary Keys, Values and Items
Python provides three important methods to access dictionary data.
keys(): Returns all keys.
values(): Returns all values.
items(): Returns all key-value pairs.
d = {"a": 10, "b": 20, "c": 30}
print(d.keys())
print(d.values())
print(d.items())
Output:
dict_keys(['a', 'b', 'c'])
dict_values([10, 20, 30])
dict_items([('a', 10), ('b', 20), ('c', 30)])
7. Checking for a Key Using Membership Operators
We can use in and not in to check whether a key exists in a dictionary.
d = {"name": "Alice", "age": 25}
print("name" in d)
print("salary" not in d)
Output:
True
True
Explanation: Membership operators check keys by default, not values.
8. Iterating Through a Dictionary
We can use a for loop to access dictionary elements.
d = {"name": "Alice", "age": 25, "city": "Chennai"}
for key in d:
print(key)
Output:
name
age
city
To print both keys and values:
for key, value in d.items():
print(key, ":", value)
Output:
name : Alice
age : 25
city : Chennai
9. Nested Dictionary
A dictionary can contain another dictionary as its value. This is called a nested dictionary.
student = {
"name": "Dheepi",
"marks": {
"math": 95,
"science": 92
}
}
print(student["name"])
print(student["marks"]["math"])
Output:
Dheepi
95
Explanation: We can access nested dictionary values by using multiple keys.
10. Dictionary Comprehension
Dictionary comprehension is a short and simple way to create dictionaries using a single expression.
squares = {x: x*x for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: The program creates a dictionary where each number is a key and its square is the corresponding value.
11. Dictionary Methods
Some commonly used dictionary methods are:
| Method | Description |
|---|---|
get() |
Returns the value of a key |
keys() |
Returns all dictionary keys |
values() |
Returns all dictionary values |
items() |
Returns key-value pairs |
update() |
Adds or updates elements |
pop() |
Removes a specified key |
popitem() |
Removes the last inserted item |
clear() |
Removes all elements |
copy() |
Creates a shallow copy |
setdefault() |
Returns a key's value or inserts a default value |
12. Using setdefault()
The setdefault() method returns the value of a key if it exists. Otherwise, it inserts the key with a specified default value.
d = {"name": "Alice", "age": 25}
d.setdefault("city", "Chennai")
print(d)
Output:
{'name': 'Alice', 'age': 25, 'city': 'Chennai'}
13. Difference Between List, Tuple, Set and Dictionary
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Syntax | [] |
() |
{} |
{key:value} |
| Ordering | Ordered | Ordered | Unordered | Insertion ordered |
| Mutability | Mutable | Immutable | Mutable | Mutable |
| Duplicates | Allowed | Allowed | Not allowed | Keys are unique |
| Access | By index | By index | No indexing | By key |
| Usage | Dynamic data | Fixed data | Unique elements | Key-value data |
Dictionaries are one of the most useful data structures in Python. They allow us to store information in key-value pairs and access data quickly using unique keys.
Understanding purpose:

Top comments (0)