Dictionary in Python
1. Introduction
• A dictionary in Python is a collection of key–value pairs.
• Each key is unique and maps to a value.
• Dictionaries are unordered (till Python 3.6, now insertion-
ordered since Python 3.7), mutable, and allow fast lookups.
• Defined using {} braces.
• my_dict = {"name": "Alice", "age": 25, "city": "New York"}
2. Accessing Items in a Dictionary
• Using keys:
print(my_dict["name"]) # Output: Alice
• Using .get():
print(my_dict.get("salary"))
# Output: Not Found
3. Mutability of a Dictionary
Dictionaries are mutable, meaning we can change them after
creation.
a) Adding a new term
my_dict["salary"] = 50000
b) Modifying an existing item
my_dict["age"] = 26
4. Traversing a Dictionary
We can loop through keys, values, or key-value pairs:
for key in my_dict:
print(key, my_dict[key])
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(key, ":", value)
5. Built-in Functions and Methods
Function/Method Description Example
len(d) Returns len(my_dict)
number of
items
dict() Creates a dict(a=1, b=2)
dictionary
keys() Returns keys my_dict.keys()
values() Returns values my_dict.values()
items() Returns key- my_dict.items()
value pairs
get(key) Returns value my_dict.get("age")
of key, or
None if
missing
update(d2) Updates with my_dict.update({"city":
another "London"})
dictionary
del d[key] Deletes an del my_dict["age"]
item by key
clear() Removes all my_dict.clear()
items
fromkeys(seq, Creates new [Link]([1,2,3], 0)
val) dict from
sequence
copy() Returns a d2 = my_dict.copy()
shallow copy
pop(key) Removes and my_dict.pop("age")
returns value
by key
popitem() Removes last my_dict.popitem()
inserted key-
value pair
setdefault(key, Returns value; my_dict.setdefault("dept",
val) sets if not "HR")
exists
max(d) Returns max max(my_dict)
key
min(d) Returns min min(my_dict)
key
sorted(d) Returns sorted sorted(my_dict)
list of keys
6. Suggested Programs
(a) Count number of times a character appears in a string
text = "dictionary"
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
print(char_count)
# Output: {'d': 1, 'i': 2, 'c': 1, 't': 1, 'o': 1, 'n': 1, 'a': 1, 'r': 1, 'y': 1}
(b) Create a dictionary with employee names and salary
employees = {
"Alice": 50000,
"Bob": 60000,
"Charlie": 70000
}
# Accessing salary of Bob
print("Bob's Salary:", employees["Bob"])
# Adding a new employee
employees["David"] = 80000
# Updating salary
employees["Alice"] = 55000
# Traversing
for name, salary in [Link]():
print(name, "earns", salary)