0% found this document useful (0 votes)
11 views

1.d.Mapping

A dictionary in Python is a mutable, unordered collection of key-value pairs that allows for fast lookups. It can be created using curly braces or the dict() constructor, and supports various methods for accessing, modifying, and removing elements. Dictionaries can also contain nested dictionaries and can be created using dictionary comprehension.

Uploaded by

kalpanapriyam213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

1.d.Mapping

A dictionary in Python is a mutable, unordered collection of key-value pairs that allows for fast lookups. It can be created using curly braces or the dict() constructor, and supports various methods for accessing, modifying, and removing elements. Dictionaries can also contain nested dictionaries and can be created using dictionary comprehension.

Uploaded by

kalpanapriyam213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Dictionary (dict) in Python – A Detailed Guide

A dictionary (dict) is a mapping data type in Python that stores data in key-value pairs.
Each key maps to a specific value, making it efficient for fast lookups.

Characteristics of a Dictionary
✅ Unordered – Items are stored in no particular order (since Python 3.7, dictionaries maintain insertion
order).
✅ Mutable – Can be modified (keys and values can be added, updated, or removed).
✅ Unique Keys – Keys must be unique (no duplicates allowed).
✅ Fast Lookup – Searching for values by key is very fast.
✅ Uses {} Braces – Defined using curly braces {} or the dict() constructor.

1. Creating a Dictionary
A dictionary is created using curly braces {} with key-value pairs separated by a colon :.

# Creating a dictionary
student = {
"name": "Alice",
"age": 22,
"course": "Computer Science"
}

print(student)

Output:

{'name': 'Alice', 'age': 22, 'course': 'Computer Science'}

Using the dict() Constructor


employee = dict(name="John", age=30, department="HR")
print(employee)

Output:

{'name': 'John', 'age': 30, 'department': 'HR'}

2. Accessing Dictionary Elements


Values in a dictionary are accessed using keys.

# Accessing values
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 22

Using get() Method (Prevents Errors)


print(student.get("course")) # Output: Computer Science
print(student.get("grade", "Not Found")) # Default value if key doesn't exist

3. Modifying a Dictionary
Updating Values
student["age"] = 23 # Modify an existing key
print(student) # Output: {'name': 'Alice', 'age': 23, 'course': 'Computer Science'}

Adding New Key-Value Pairs


student["grade"] = "A"
print(student) # Output: {'name': 'Alice', 'age': 23, 'course': 'Computer Science',
'grade': 'A'}

4. Removing Elements
Using pop() – Removes Key and Returns Value
age = student.pop("age")
print(age) # Output: 23
print(student) # Output: {'name': 'Alice', 'course': 'Computer Science', 'grade': 'A'}

Using del – Deletes Key Completely


del student["grade"]
print(student) # Output: {'name': 'Alice', 'course': 'Computer Science'}

Using popitem() – Removes and Returns Last Inserted Key-Value Pair


student.popitem()
print(student) # Output: {'name': 'Alice'}

Using clear() – Removes All Items


student.clear()
print(student) # Output: {}

5. Looping Through a Dictionary

Looping Through Keys


for key in student:
print(key) # Output: name, age, course

Looping Through Values


for value in student.values():
print(value) # Output: Alice, 22, Computer Science

Looping Through Key-Value Pairs


for key, value in student.items():
print(key, ":", value)

Output:

name : Alice
age : 22
course : Computer Science

6. Dictionary Methods
Method Description
dict.keys() Returns all keys
dict.values() Returns all values
dict.items() Returns key-value pairs
dict.get(key, default) Returns value or default if key not found
dict.pop(key) Removes a key and returns its value
dict.popitem() Removes and returns the last key-value pair
dict.clear() Removes all items
dict.update(dict2) Merges another dictionary into it

7. Nested Dictionaries
A dictionary can contain another dictionary as a value.

students = {
"Alice": {"age": 22, "course": "CS"},
"Bob": {"age": 21, "course": "IT"}
}

print(students["Alice"]["course"]) # Output: CS

8. Dictionary Comprehension
Creating a Dictionary with Squares of Numbers
squares = {x: x*x for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
9. Practical Examples
Example 1: Counting Word Frequency in a Sentence
sentence = "apple banana apple mango banana apple"
words = sentence.split()

word_count = {}

for word in words:


word_count[word] = word_count.get(word, 0) + 1

print(word_count) # Output: {'apple': 3, 'banana': 2, 'mango': 1}

Example 2: Using a Dictionary to Store Student Records


students = {
101: {"name": "Alice", "marks": 85},
102: {"name": "Bob", "marks": 90},
103: {"name": "Charlie", "marks": 78}
}

for roll_no, info in students.items():


print(f"Roll No: {roll_no}, Name: {info['name']}, Marks: {info['marks']}")

Output:

Roll No: 101, Name: Alice, Marks: 85


Roll No: 102, Name: Bob, Marks: 90
Roll No: 103, Name: Charlie, Marks: 78

Summary
Feature Dictionary (dict)
Mutable? Yes
Ordered? Yes (since Python 3.7)
Unique Keys? Yes
Fast Lookup? Yes
Nested? Yes

You might also like