Python Dictionary 1
1. Introduction A dictionary in Python is an unordered, mutable
collection of elements stored as key–value pairs.
Key Characteristics:
Stores data in key: value format
Keys must be unique and immutable (e.g., strings, numbers, tuples)
Values can be of any data type
Dictionaries are mutable (can be changed after creation)
Example: d = {"name": "Alice", "age": 25, "marks": 90}
print(d)
2. Accessing Items Using Keys Values in a dictionary are accessed
using their keys.
Example: d = {"name": "Alice", "age": 25}
print(d["name"]) # Alice
print(d["age"]) # 25
Using get() method:
print([Link]("name")) # Alice
print([Link]("city")) # None (no
error)
Difference:
d[key] → gives error if key not found
[Link](key) → returns None (or default value)
3. Mutability of Dictionary
a) Adding a New Item d = {"name": "Alice"}
d["age"] = 25
print(d) # {'name': 'Alice', 'age': 25}
b) Modifying an Existing Item d = {"name": "Alice", "age": 25}
d["age"] = 30
print(d) # {'name': 'Alice', 'age': 30}
4. Traversing a Dictionary Traversal means iterating through dictionary
elements.
a) Traversing Keys d = {"a": 1, "b": 2, "c": 3}
for key in d:
print(key)
b) Traversing Values for value in [Link]():
print(value)
Python Dictionary 2
c) Traversing Key-Value Pairs for key, value in
[Link]():
print(key, value)
5. Built-in Functions and Methods
a) len() Returns number of items. d = {"a": 1, "b": 2}
print(len(d)) # 2
b) dict() Creates a dictionary. d = dict(a=1, b=2)
print(d)
c) keys() Returns all keys. print([Link]())
d) values() Returns all values. print([Link]())
e) items() Returns key-value pairs. print([Link]())
f) get() Returns value of a key safely. print([Link]("a"))
g) update() Updates dictionary with another dictionary. d = {"a": 1}
[Link]({"b": 2})
print(d)
h) del() function Deletes a specific item. d = {"a": 1, "b": 2}
del d["a"]
print(d)
i) del keyword (entire dictionary) del d
j) clear() Removes all items.
d = {"a": 1, "b": 2}
[Link]()
print(d) # {}
k) fromkeys() Creates dictionary with given keys and a common value.
keys = ["a", "b", "c"]
d = [Link](keys, 0)
print(d)
l) copy() Creates a shallow copy.
d1 = {"a": 1}
Python Dictionary 3
d2 = [Link]()
m) pop() Removes and returns value of given key.
d = {"a": 1, "b": 2}
print([Link]("a")) # 1
n) popitem() Removes and returns last inserted item.
d = {"a": 1, "b": 2}
print([Link]())
o) setdefault() Returns value of key; inserts key if not present.
d = {"a": 1}
[Link]("b", 2)
print(d)
p) max() Returns maximum key.
d = {"a": 10, "b": 20}
print(max(d)) # b
q) min() Returns minimum key. print(min(d)) # a
r) sorted() Returns sorted list of keys. print(sorted(d))
6. Conclusion
Python dictionaries are:
Powerful for storing key-value structured data
Efficient for fast lookup using keys
Flexible due to their mutability
They are widely used in real-world applications like:
Databases
JSON data handling
Configuration storage